@cldmv/holdmytask 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,584 @@
1
+ /**
2
+ * @Project: @cldmv/holdmytask
3
+ * @Filename: /src/hold-my-task.mjs
4
+ * @Date: 2025-11-08 17:43:19 -08:00 (1762652599)
5
+ * @Author: Nate Hyson <CLDMV>
6
+ * @Email: <Shinrai@users.noreply.github.com>
7
+ * -----
8
+ * @Last modified by: Nate Hyson <CLDMV> (Shinrai@users.noreply.github.com)
9
+ * @Last modified time: 2025-11-09 18:23:26 -08:00 (1762741406)
10
+ * -----
11
+ * @Copyright: Copyright (c) 2013-2025 Catalyzed Motivation Inc. All rights reserved.
12
+ */
13
+
14
+ import { EventEmitter } from "events";
15
+ import { MinHeap } from "./utils.mjs";
16
+
17
+ /**
18
+ * A sophisticated task queue that manages task execution with priorities, delays, and concurrency control.
19
+ * Tasks can be scheduled with timestamps, priorities, and completion delays between tasks of the same priority.
20
+ * Supports both callback and promise-based APIs with comprehensive lifecycle management.
21
+ * @extends EventEmitter
22
+ */
23
+ export class HoldMyTask extends EventEmitter {
24
+ /**
25
+ * Creates a new HoldMyTask queue instance.
26
+ * @param {Object} [options={}] - Configuration options for the task queue
27
+ * @param {number} [options.concurrency=1] - Maximum number of tasks to run concurrently
28
+ * @param {number} [options.tick=25] - Scheduler tick interval in milliseconds
29
+ * @param {boolean} [options.autoStart=true] - Whether to automatically start the scheduler
30
+ * @param {number} [options.defaultPriority=0] - Default priority for tasks (higher numbers = higher priority)
31
+ * @param {number} [options.maxQueue=Infinity] - Maximum number of tasks that can be queued
32
+ * @param {Object} [options.delays={}] - Map of priority levels to delay times in milliseconds between task completions
33
+ * @example
34
+ * const queue = new HoldMyTask({
35
+ * concurrency: 2,
36
+ * tick: 50,
37
+ * defaultPriority: 1,
38
+ * delays: { 0: 1000, 1: 500 }
39
+ * });
40
+ */
41
+ constructor(options = {}) {
42
+ super();
43
+ this.options = {
44
+ concurrency: 1,
45
+ tick: 25,
46
+ autoStart: true,
47
+ defaultPriority: 0,
48
+ maxQueue: Infinity,
49
+ delays: {}, // priority -> delay in ms between tasks of that priority
50
+ ...options
51
+ };
52
+
53
+ // Initialize heaps
54
+ this.pendingHeap = new MinHeap((a, b) => a.readyAt - b.readyAt);
55
+ this.readyHeap = new MinHeap((a, b) => {
56
+ if (a.priority !== b.priority) return b.priority - a.priority; // Higher priority first
57
+ if (a.readyAt !== b.readyAt) return a.readyAt - b.readyAt; // Earlier ready first
58
+ return a.enqueueSeq - b.enqueueSeq; // Earlier enqueue first
59
+ });
60
+
61
+ this.running = new Set();
62
+ this.tasks = new Map();
63
+ this.nextId = 1;
64
+ this.enqueueSeq = 1;
65
+ this.isActive = false;
66
+ this.destroyed = false;
67
+ this.lastCompletedPriority = null;
68
+ this.nextAvailableTime = 0; // For delays after task completion
69
+
70
+ if (this.options.autoStart) {
71
+ this.resume();
72
+ }
73
+ }
74
+
75
+ /**
76
+ * Adds a task to the queue for execution. Supports both callback and promise-based APIs.
77
+ * @param {Function} task - The task function to execute. Can be sync or async.
78
+ * @param {Function|Object} [optionsOrCallback] - Either a callback function or options object
79
+ * @param {Object} [options={}] - Additional options (if callback was provided as second parameter)
80
+ * @param {number} [options.priority] - Task priority (higher numbers run first)
81
+ * @param {number} [options.timestamp] - When the task should be ready to run (milliseconds since epoch)
82
+ * @param {AbortSignal} [options.signal] - AbortSignal to cancel the task
83
+ * @param {number} [options.timeout] - Task timeout in milliseconds
84
+ * @param {number} [options.delay] - Delay after task completion before next task of same priority
85
+ * @param {boolean} [options.bypassDelay] - If true, skip any active delay period and start immediately
86
+ * @param {*} [options.metadata] - Arbitrary metadata to attach to the task
87
+ * @returns {Promise|Object} Promise (if no callback) or task control object with id, cancel, status methods
88
+ * @throws {Error} If queue is destroyed or full
89
+ * @example
90
+ * // Promise API
91
+ * const result = await queue.enqueue(async () => fetchData());
92
+ *
93
+ * // Callback API
94
+ * queue.enqueue(() => processData(), (err, result) => {
95
+ * if (err) console.error(err);
96
+ * else console.log(result);
97
+ * });
98
+ *
99
+ * // With options
100
+ * const task = queue.enqueue(myTask, { priority: 5, timeout: 30000 });
101
+ *
102
+ * // Bypass current delay for urgent task
103
+ * const urgent = queue.enqueue(urgentTask, { priority: 10, bypassDelay: true });
104
+ *
105
+ * // Alternative: use delay: -1 to bypass
106
+ * const urgent2 = queue.enqueue(urgentTask, { priority: 10, delay: -1 });
107
+ */
108
+ enqueue(task, optionsOrCallback, options = {}) {
109
+ if (this.destroyed) {
110
+ throw new Error("Queue is destroyed");
111
+ }
112
+
113
+ if (this.tasks.size >= this.options.maxQueue) {
114
+ throw new Error("Queue is full");
115
+ }
116
+
117
+ // Handle dual API: callback can be second or third parameter
118
+ let callback = null;
119
+ let finalOptions = options;
120
+
121
+ if (typeof optionsOrCallback === "function") {
122
+ callback = optionsOrCallback;
123
+ } else if (optionsOrCallback && typeof optionsOrCallback === "object") {
124
+ finalOptions = { ...optionsOrCallback, ...options };
125
+ }
126
+
127
+ const id = String(this.nextId++);
128
+ const now = this.now();
129
+ const readyAt = finalOptions.timestamp ?? now;
130
+
131
+ const item = {
132
+ id,
133
+ task,
134
+ callback,
135
+ priority: finalOptions.priority ?? this.options.defaultPriority,
136
+ readyAt,
137
+ enqueueSeq: this.enqueueSeq++,
138
+ status: "pending",
139
+ signal: finalOptions.signal,
140
+ timeout: finalOptions.timeout,
141
+ delay: finalOptions.delay, // completion delay
142
+ bypassDelay: finalOptions.bypassDelay || finalOptions.delay === -1, // bypass current delay period
143
+ metadata: finalOptions.metadata
144
+ };
145
+
146
+ this.tasks.set(id, item);
147
+ this.pendingHeap.push(item);
148
+
149
+ // Check if signal is already aborted
150
+ if (finalOptions.signal?.aborted) {
151
+ this.cancelTask(id, "Aborted");
152
+ } else if (callback) {
153
+ // For callback API, the queue handles signal abortion
154
+ finalOptions.signal?.addEventListener("abort", () => {
155
+ this.cancelTask(id, "Aborted");
156
+ });
157
+ }
158
+ // For promise API, assume the task handles the signal itself
159
+
160
+ if (this.isActive) {
161
+ this.scheduleNextTick();
162
+ }
163
+
164
+ const tasks = this.tasks; // Capture reference
165
+ const taskHandle = {
166
+ id,
167
+ cancel: (reason) => this.cancelTask(id, reason),
168
+ status: () => tasks.get(id)?.status ?? "canceled",
169
+ get startedAt() {
170
+ return tasks.get(id)?.startedAt;
171
+ },
172
+ get finishedAt() {
173
+ return tasks.get(id)?.finishedAt;
174
+ },
175
+ get result() {
176
+ return tasks.get(id)?.result;
177
+ },
178
+ get error() {
179
+ return tasks.get(id)?.error;
180
+ }
181
+ };
182
+
183
+ // Return Promise if no callback provided
184
+ if (!callback) {
185
+ const promise = new Promise((resolve, reject) => {
186
+ item.resolve = resolve;
187
+ item.reject = reject;
188
+ });
189
+
190
+ // Attach task handle properties to the promise with live getters
191
+ const tasksRef = this.tasks;
192
+ Object.defineProperty(promise, "id", { value: id, enumerable: true });
193
+ Object.defineProperty(promise, "cancel", { value: (reason) => this.cancelTask(id, reason), enumerable: true });
194
+ Object.defineProperty(promise, "status", { value: () => tasksRef.get(id)?.status ?? "canceled", enumerable: true });
195
+ Object.defineProperty(promise, "startedAt", { get: () => tasksRef.get(id)?.startedAt, enumerable: true });
196
+ Object.defineProperty(promise, "finishedAt", { get: () => tasksRef.get(id)?.finishedAt, enumerable: true });
197
+ Object.defineProperty(promise, "result", { get: () => tasksRef.get(id)?.result, enumerable: true });
198
+ Object.defineProperty(promise, "error", { get: () => tasksRef.get(id)?.error, enumerable: true });
199
+
200
+ return promise;
201
+ }
202
+
203
+ return taskHandle;
204
+ }
205
+
206
+ /**
207
+ * Cancels a pending task by ID.
208
+ * @param {string} id - The task ID to cancel
209
+ * @param {string} [reason="Task canceled"] - Reason for cancellation
210
+ * @returns {void}
211
+ * @example
212
+ * const task = queue.enqueue(() => longRunningTask());
213
+ * queue.cancelTask(task.id, "User requested cancellation");
214
+ */
215
+ cancelTask(id, reason) {
216
+ const item = this.tasks.get(id);
217
+ if (!item || item.status !== "pending") return;
218
+
219
+ item.status = "canceled";
220
+ item.finishedAt = this.now();
221
+ this.tasks.delete(id);
222
+ this.emit("cancel", item, reason);
223
+
224
+ // Reject promise if no callback
225
+ if (!item.callback && item.reject) {
226
+ item.reject(new Error(reason || "Task canceled"));
227
+ }
228
+ }
229
+
230
+ /**
231
+ * Pauses the task queue, stopping execution of new tasks.
232
+ * Currently running tasks will continue to completion.
233
+ * @returns {void}
234
+ * @example
235
+ * queue.pause();
236
+ * // Queue stops processing new tasks
237
+ */
238
+ pause() {
239
+ this.isActive = false;
240
+ this.clearTimers();
241
+ }
242
+
243
+ /**
244
+ * Resumes the task queue after being paused.
245
+ * @returns {void}
246
+ * @example
247
+ * queue.resume();
248
+ * // Queue resumes processing tasks
249
+ */
250
+ resume() {
251
+ if (this.destroyed) return;
252
+ this.isActive = true;
253
+ // If there are pending tasks, run scheduler immediately
254
+ if (this.pendingHeap.size() > 0 || this.readyHeap.size() > 0) {
255
+ this.schedulerTick();
256
+ }
257
+ this.scheduleNextTick();
258
+ }
259
+
260
+ /**
261
+ * Clears all pending and ready tasks from the queue.
262
+ * Currently running tasks will continue to completion.
263
+ * @returns {void}
264
+ * @example
265
+ * queue.clear();
266
+ * // All queued tasks are removed
267
+ */
268
+ clear() {
269
+ // Cancel all pending tasks
270
+ const pendingTasks = [];
271
+ while (this.pendingHeap.size() > 0) {
272
+ const item = this.pendingHeap.pop();
273
+ if (item && item.status === "pending") {
274
+ pendingTasks.push(item);
275
+ }
276
+ }
277
+ for (const item of pendingTasks) {
278
+ item.status = "canceled";
279
+ this.emit("cancel", item);
280
+ }
281
+
282
+ this.pendingHeap = new MinHeap((a, b) => a.readyAt - b.readyAt);
283
+ this.readyHeap = new MinHeap((a, b) => {
284
+ if (a.priority !== b.priority) return b.priority - a.priority;
285
+ if (a.readyAt !== b.readyAt) return a.readyAt - b.readyAt;
286
+ return a.enqueueSeq - b.enqueueSeq;
287
+ });
288
+ this.tasks.clear();
289
+ }
290
+
291
+ /**
292
+ * Returns the total number of tasks in the queue (pending, ready, and running).
293
+ * @returns {number} Total number of tasks
294
+ * @example
295
+ * const totalTasks = queue.size(); // 5
296
+ */
297
+ size() {
298
+ return this.tasks.size;
299
+ }
300
+
301
+ /**
302
+ * Returns the number of currently running tasks.
303
+ * @returns {number} Number of running tasks
304
+ * @example
305
+ * const runningTasks = queue.inflight(); // 2
306
+ */
307
+ inflight() {
308
+ return this.running.size;
309
+ }
310
+
311
+ /**
312
+ * Destroys the queue, canceling all tasks and stopping the scheduler.
313
+ * Once destroyed, the queue cannot be reused.
314
+ * @returns {void}
315
+ * @example
316
+ * queue.destroy();
317
+ * // Queue is permanently shut down
318
+ */
319
+ destroy() {
320
+ this.destroyed = true;
321
+ this.pause();
322
+ this.clear();
323
+ this.emit("drain");
324
+ }
325
+
326
+ /**
327
+ * Returns the current timestamp in milliseconds.
328
+ * @returns {number} Current timestamp
329
+ * @example
330
+ * const timestamp = queue.now(); // 1699564800000
331
+ */
332
+ now() {
333
+ return this.options.now?.() ?? Date.now();
334
+ }
335
+
336
+ /**
337
+ * Schedules the next scheduler tick based on when tasks become ready.
338
+ * @returns {void}
339
+ * @private
340
+ */
341
+ scheduleNextTick() {
342
+ if (!this.isActive || this.destroyed) return;
343
+
344
+ this.clearTimers();
345
+
346
+ const now = this.now();
347
+ let nextTime = Infinity;
348
+
349
+ // Check pending heap for next ready time
350
+ const nextPending = this.pendingHeap.peek();
351
+ if (nextPending) {
352
+ nextTime = nextPending.readyAt;
353
+ }
354
+
355
+ // Check if we have a delay until next tasks can start
356
+ if (this.nextAvailableTime > now) {
357
+ nextTime = Math.min(nextTime, this.nextAvailableTime);
358
+ }
359
+
360
+ // If next event is imminent or past, run immediately
361
+ if (nextTime <= now + this.options.tick) {
362
+ this.intervalId = setInterval(() => this.schedulerTick(), this.options.tick);
363
+ } else {
364
+ // Use timeout for distant events
365
+ const delay = Math.min(nextTime - now, 2147483647); // Max 32-bit int
366
+ this.timeoutId = setTimeout(() => this.schedulerTick(), delay);
367
+ }
368
+ }
369
+
370
+ /**
371
+ * Main scheduler tick that moves ready tasks and starts execution.
372
+ * @returns {void}
373
+ * @private
374
+ */
375
+ schedulerTick() {
376
+ const now = this.now();
377
+
378
+ // Move ready tasks from pending to ready heap
379
+ let nextPending = this.pendingHeap.peek();
380
+ while (nextPending && nextPending.readyAt <= now) {
381
+ const task = this.pendingHeap.pop();
382
+ if (task && task.status === "pending") {
383
+ task.status = "ready";
384
+ this.readyHeap.push(task);
385
+ }
386
+ nextPending = this.pendingHeap.peek();
387
+ }
388
+
389
+ // Start tasks up to concurrency limit
390
+ let hasWaitingTasks = false;
391
+ const currentTime = this.now();
392
+ const delay = this.lastCompletedPriority !== null ? this.options.delays[this.lastCompletedPriority] || 0 : 0;
393
+ const delayActive = delay > 0 && currentTime < this.nextAvailableTime;
394
+
395
+ while (this.running.size < this.options.concurrency && this.readyHeap.size() > 0) {
396
+ const task = this.readyHeap.peek();
397
+ if (!task) break;
398
+
399
+ const canStart = task.bypassDelay || !delayActive;
400
+
401
+ if (canStart) {
402
+ this.readyHeap.pop(); // Remove it from heap
403
+ this.startTask(task);
404
+ } else {
405
+ // Can't start due to delay - check if there are any bypass tasks in the heap
406
+ const heapArray = this.readyHeap.heap.slice(); // Copy heap array
407
+ let foundBypassTask = false;
408
+
409
+ for (let i = 0; i < heapArray.length; i++) {
410
+ if (heapArray[i].bypassDelay) {
411
+ foundBypassTask = true;
412
+ // Remove the bypass task from heap and start it
413
+ // We need to rebuild the heap without this task
414
+ const bypassTask = heapArray[i];
415
+ const remainingTasks = heapArray.filter((t) => t.id !== bypassTask.id);
416
+ this.readyHeap.heap = [];
417
+ for (const t of remainingTasks) {
418
+ this.readyHeap.push(t);
419
+ }
420
+ this.startTask(bypassTask);
421
+ break;
422
+ }
423
+ }
424
+
425
+ if (!foundBypassTask) {
426
+ // No bypass tasks available, mark that we have waiting tasks
427
+ hasWaitingTasks = true;
428
+ break;
429
+ }
430
+ }
431
+ }
432
+
433
+ // Schedule next tick if there are pending tasks or tasks that might become available
434
+ if (this.pendingHeap.size() > 0 || this.readyHeap.size() > 0 || hasWaitingTasks) {
435
+ this.scheduleNextTick();
436
+ }
437
+ }
438
+
439
+ /**
440
+ * Starts execution of a ready task.
441
+ * @param {Object} item - The task item to execute
442
+ * @returns {Promise<void>}
443
+ * @private
444
+ */
445
+ async startTask(item) {
446
+ if (item.status !== "ready") return;
447
+
448
+ // For promise API, check if signal is already aborted
449
+ if (!item.callback && item.signal?.aborted) {
450
+ item.reject(new Error("Task was aborted"));
451
+ return;
452
+ }
453
+
454
+ item.status = "running";
455
+ item.startedAt = this.now();
456
+ this.running.add(item);
457
+ this.emit("start", item);
458
+
459
+ // Create abort controller for timeout
460
+ const abortController = new AbortController();
461
+ let timeoutId;
462
+
463
+ try {
464
+ // Set up timeout if specified
465
+ let timeoutId;
466
+ let timeoutPromise;
467
+
468
+ if (item.timeout) {
469
+ timeoutPromise = new Promise((_, reject) => {
470
+ timeoutId = setTimeout(() => {
471
+ abortController.abort();
472
+ reject(new Error(`Task timed out after ${item.timeout}ms`));
473
+ }, item.timeout);
474
+ });
475
+ }
476
+
477
+ // Run the task
478
+ const taskPromise = item.task(abortController.signal);
479
+ const result = item.timeout ? await Promise.race([taskPromise, timeoutPromise]) : await taskPromise;
480
+ item.result = result;
481
+ item.status = "completed";
482
+ item.finishedAt = this.now();
483
+
484
+ // Clear timeout if it was set
485
+ if (timeoutId) {
486
+ clearTimeout(timeoutId);
487
+ }
488
+
489
+ this.emit("success", item);
490
+
491
+ // Call completion callback or resolve promise
492
+ if (item.callback) {
493
+ try {
494
+ item.callback(null, result);
495
+ } catch (callbackError) {
496
+ // Callback threw an error, but task succeeded
497
+ this.emit("error", { ...item, error: callbackError, callbackError: true });
498
+ }
499
+ } else if (item.resolve) {
500
+ item.resolve(result);
501
+ }
502
+ } catch (error) {
503
+ item.error = error;
504
+ item.status = error.message.includes("timed out")
505
+ ? "timeout"
506
+ : abortController.signal.aborted || error.name === "AbortError"
507
+ ? "canceled"
508
+ : "error";
509
+ item.finishedAt = this.now();
510
+
511
+ // Emit error event only for callback API (promise API conveys error via rejection)
512
+ if (item.callback) {
513
+ this.emit("error", item);
514
+ }
515
+
516
+ // Call completion callback or reject promise
517
+ if (item.callback) {
518
+ try {
519
+ const errorPayload =
520
+ item.status === "timeout"
521
+ ? { type: "timeout", message: error.message }
522
+ : abortController.signal.aborted || error.name === "AbortError"
523
+ ? { type: "canceled", message: "Task was aborted" }
524
+ : { type: "error", error };
525
+ item.callback(errorPayload, null);
526
+ } catch (callbackError) {
527
+ // Callback threw an error
528
+ this.emit("error", { ...item, error: callbackError, callbackError: true });
529
+ }
530
+ } else if (item.reject) {
531
+ item.reject(error);
532
+ }
533
+ } finally {
534
+ // Clear timeout
535
+ if (timeoutId) {
536
+ clearTimeout(timeoutId);
537
+ }
538
+
539
+ this.running.delete(item);
540
+ if (item.status !== "completed") {
541
+ this.tasks.delete(item.id); // Clean up failed/canceled tasks
542
+ }
543
+
544
+ // Update delay tracking after task completion
545
+ const completedPriority = item.priority;
546
+ const taskDelay = item.delay;
547
+ const globalDelay = this.options.delays[completedPriority] || 0;
548
+ const delay = taskDelay !== undefined ? taskDelay : globalDelay;
549
+ if (delay > 0) {
550
+ this.lastCompletedPriority = completedPriority;
551
+ this.nextAvailableTime = this.now() + delay;
552
+ } else {
553
+ this.lastCompletedPriority = null;
554
+ this.nextAvailableTime = 0;
555
+ }
556
+
557
+ // Check for drain after a microtask tick to ensure event handlers complete
558
+ setImmediate(() => {
559
+ if (this.running.size === 0 && this.pendingHeap.size() === 0 && this.readyHeap.size() === 0) {
560
+ this.emit("drain");
561
+ } else if (this.isActive) {
562
+ // More tasks to run, run scheduler immediately
563
+ this.schedulerTick();
564
+ }
565
+ });
566
+ }
567
+ }
568
+
569
+ /**
570
+ * Clears all active timers (intervals and timeouts).
571
+ * @returns {void}
572
+ * @private
573
+ */
574
+ clearTimers() {
575
+ if (this.intervalId) {
576
+ clearInterval(this.intervalId);
577
+ this.intervalId = undefined;
578
+ }
579
+ if (this.timeoutId) {
580
+ clearTimeout(this.timeoutId);
581
+ this.timeoutId = undefined;
582
+ }
583
+ }
584
+ }
package/dist/utils.mjs ADDED
@@ -0,0 +1,120 @@
1
+ /**
2
+ * @Project: @cldmv/holdmytask
3
+ * @Filename: /src/utils.mjs
4
+ * @Date: 2025-11-08 17:43:09 -08:00 (1762652589)
5
+ * @Author: Nate Hyson <CLDMV>
6
+ * @Email: <Shinrai@users.noreply.github.com>
7
+ * -----
8
+ * @Last modified by: Nate Hyson <CLDMV> (Shinrai@users.noreply.github.com)
9
+ * @Last modified time: 2025-11-09 16:22:05 -08:00 (1762734125)
10
+ * -----
11
+ * @Copyright: Copyright (c) 2013-2025 Catalyzed Motivation Inc. All rights reserved.
12
+ */
13
+
14
+ /**
15
+ * A min-heap implementation with custom comparison function.
16
+ * Maintains the heap property where parent nodes are smaller than their children.
17
+ */
18
+ export class MinHeap {
19
+ /**
20
+ * Creates a new MinHeap with a custom comparison function.
21
+ * @param {Function} compare - Comparison function that returns negative if a < b, positive if a > b, 0 if equal
22
+ * @example
23
+ * // Priority queue (higher priority = smaller value)
24
+ * const heap = new MinHeap((a, b) => a.priority - b.priority);
25
+ */
26
+ constructor(compare) {
27
+ this.heap = [];
28
+ this.compare = compare;
29
+ }
30
+
31
+ /**
32
+ * Adds an item to the heap, maintaining heap property.
33
+ * @param {*} item - The item to add to the heap
34
+ * @returns {void}
35
+ * @example
36
+ * heap.push({ value: 5, priority: 1 });
37
+ */
38
+ push(item) {
39
+ this.heap.push(item);
40
+ this.bubbleUp(this.heap.length - 1);
41
+ }
42
+
43
+ /**
44
+ * Removes and returns the minimum item from the heap.
45
+ * @returns {*|undefined} The minimum item, or undefined if heap is empty
46
+ * @example
47
+ * const min = heap.pop(); // Returns item with smallest comparison value
48
+ */
49
+ pop() {
50
+ if (this.heap.length === 0) return undefined;
51
+ const root = this.heap[0];
52
+ const last = this.heap.pop();
53
+ if (this.heap.length > 0) {
54
+ this.heap[0] = last;
55
+ this.sinkDown(0);
56
+ }
57
+ return root;
58
+ }
59
+
60
+ /**
61
+ * Returns the minimum item without removing it from the heap.
62
+ * @returns {*|undefined} The minimum item, or undefined if heap is empty
63
+ * @example
64
+ * const min = heap.peek(); // Look at minimum without removing
65
+ */
66
+ peek() {
67
+ return this.heap[0];
68
+ }
69
+
70
+ /**
71
+ * Returns the number of items in the heap.
72
+ * @returns {number} The size of the heap
73
+ * @example
74
+ * const count = heap.size(); // 5
75
+ */
76
+ size() {
77
+ return this.heap.length;
78
+ }
79
+
80
+ /**
81
+ * Moves an item up the heap to maintain heap property after insertion.
82
+ * @param {number} index - Index of the item to bubble up
83
+ * @returns {void}
84
+ * @private
85
+ */
86
+ bubbleUp(index) {
87
+ while (index > 0) {
88
+ const parentIndex = Math.floor((index - 1) / 2);
89
+ if (this.compare(this.heap[index], this.heap[parentIndex]) >= 0) break;
90
+ [this.heap[index], this.heap[parentIndex]] = [this.heap[parentIndex], this.heap[index]];
91
+ index = parentIndex;
92
+ }
93
+ }
94
+
95
+ /**
96
+ * Moves an item down the heap to maintain heap property after removal.
97
+ * @param {number} index - Index of the item to sink down
98
+ * @returns {void}
99
+ * @private
100
+ */
101
+ sinkDown(index) {
102
+ const length = this.heap.length;
103
+ while (true) {
104
+ let left = 2 * index + 1;
105
+ let right = 2 * index + 2;
106
+ let smallest = index;
107
+
108
+ if (left < length && this.compare(this.heap[left], this.heap[smallest]) < 0) {
109
+ smallest = left;
110
+ }
111
+ if (right < length && this.compare(this.heap[right], this.heap[smallest]) < 0) {
112
+ smallest = right;
113
+ }
114
+ if (smallest === index) break;
115
+
116
+ [this.heap[index], this.heap[smallest]] = [this.heap[smallest], this.heap[index]];
117
+ index = smallest;
118
+ }
119
+ }
120
+ }