binary-tree-typed 2.4.4 → 2.5.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.
Files changed (85) hide show
  1. package/README.md +0 -84
  2. package/dist/cjs/index.cjs +965 -420
  3. package/dist/cjs/index.cjs.map +1 -1
  4. package/dist/cjs-legacy/index.cjs +962 -417
  5. package/dist/cjs-legacy/index.cjs.map +1 -1
  6. package/dist/esm/index.mjs +965 -421
  7. package/dist/esm/index.mjs.map +1 -1
  8. package/dist/esm-legacy/index.mjs +962 -418
  9. package/dist/esm-legacy/index.mjs.map +1 -1
  10. package/dist/types/common/error.d.ts +23 -0
  11. package/dist/types/common/index.d.ts +1 -0
  12. package/dist/types/data-structures/base/iterable-element-base.d.ts +1 -1
  13. package/dist/types/data-structures/binary-tree/avl-tree.d.ts +128 -51
  14. package/dist/types/data-structures/binary-tree/binary-indexed-tree.d.ts +210 -164
  15. package/dist/types/data-structures/binary-tree/binary-tree.d.ts +439 -78
  16. package/dist/types/data-structures/binary-tree/bst.d.ts +311 -28
  17. package/dist/types/data-structures/binary-tree/red-black-tree.d.ts +217 -31
  18. package/dist/types/data-structures/binary-tree/segment-tree.d.ts +218 -152
  19. package/dist/types/data-structures/binary-tree/tree-map.d.ts +1281 -5
  20. package/dist/types/data-structures/binary-tree/tree-multi-map.d.ts +1087 -201
  21. package/dist/types/data-structures/binary-tree/tree-multi-set.d.ts +858 -65
  22. package/dist/types/data-structures/binary-tree/tree-set.d.ts +1133 -5
  23. package/dist/types/data-structures/graph/abstract-graph.d.ts +44 -0
  24. package/dist/types/data-structures/graph/directed-graph.d.ts +220 -47
  25. package/dist/types/data-structures/graph/map-graph.d.ts +59 -1
  26. package/dist/types/data-structures/graph/undirected-graph.d.ts +218 -59
  27. package/dist/types/data-structures/hash/hash-map.d.ts +230 -77
  28. package/dist/types/data-structures/heap/heap.d.ts +287 -99
  29. package/dist/types/data-structures/heap/max-heap.d.ts +46 -0
  30. package/dist/types/data-structures/heap/min-heap.d.ts +59 -0
  31. package/dist/types/data-structures/linked-list/doubly-linked-list.d.ts +286 -44
  32. package/dist/types/data-structures/linked-list/singly-linked-list.d.ts +278 -65
  33. package/dist/types/data-structures/linked-list/skip-linked-list.d.ts +415 -12
  34. package/dist/types/data-structures/matrix/matrix.d.ts +331 -0
  35. package/dist/types/data-structures/priority-queue/max-priority-queue.d.ts +57 -0
  36. package/dist/types/data-structures/priority-queue/min-priority-queue.d.ts +60 -0
  37. package/dist/types/data-structures/priority-queue/priority-queue.d.ts +60 -0
  38. package/dist/types/data-structures/queue/deque.d.ts +313 -66
  39. package/dist/types/data-structures/queue/queue.d.ts +211 -42
  40. package/dist/types/data-structures/stack/stack.d.ts +174 -32
  41. package/dist/types/data-structures/trie/trie.d.ts +213 -43
  42. package/dist/types/types/data-structures/binary-tree/segment-tree.d.ts +1 -1
  43. package/dist/types/types/data-structures/linked-list/skip-linked-list.d.ts +1 -4
  44. package/dist/types/types/data-structures/queue/deque.d.ts +6 -0
  45. package/dist/umd/binary-tree-typed.js +959 -414
  46. package/dist/umd/binary-tree-typed.js.map +1 -1
  47. package/dist/umd/binary-tree-typed.min.js +3 -3
  48. package/dist/umd/binary-tree-typed.min.js.map +1 -1
  49. package/package.json +2 -2
  50. package/src/common/error.ts +60 -0
  51. package/src/common/index.ts +2 -0
  52. package/src/data-structures/base/iterable-element-base.ts +2 -2
  53. package/src/data-structures/binary-tree/avl-tree.ts +134 -51
  54. package/src/data-structures/binary-tree/binary-indexed-tree.ts +303 -247
  55. package/src/data-structures/binary-tree/binary-tree.ts +542 -121
  56. package/src/data-structures/binary-tree/bst.ts +346 -37
  57. package/src/data-structures/binary-tree/red-black-tree.ts +309 -96
  58. package/src/data-structures/binary-tree/segment-tree.ts +372 -248
  59. package/src/data-structures/binary-tree/tree-map.ts +1292 -13
  60. package/src/data-structures/binary-tree/tree-multi-map.ts +1098 -215
  61. package/src/data-structures/binary-tree/tree-multi-set.ts +863 -69
  62. package/src/data-structures/binary-tree/tree-set.ts +1143 -15
  63. package/src/data-structures/graph/abstract-graph.ts +106 -1
  64. package/src/data-structures/graph/directed-graph.ts +223 -47
  65. package/src/data-structures/graph/map-graph.ts +59 -1
  66. package/src/data-structures/graph/undirected-graph.ts +299 -59
  67. package/src/data-structures/hash/hash-map.ts +243 -79
  68. package/src/data-structures/heap/heap.ts +291 -102
  69. package/src/data-structures/heap/max-heap.ts +48 -3
  70. package/src/data-structures/heap/min-heap.ts +59 -0
  71. package/src/data-structures/linked-list/doubly-linked-list.ts +286 -44
  72. package/src/data-structures/linked-list/singly-linked-list.ts +278 -65
  73. package/src/data-structures/linked-list/skip-linked-list.ts +689 -90
  74. package/src/data-structures/matrix/matrix.ts +425 -22
  75. package/src/data-structures/priority-queue/max-priority-queue.ts +59 -3
  76. package/src/data-structures/priority-queue/min-priority-queue.ts +60 -0
  77. package/src/data-structures/priority-queue/priority-queue.ts +60 -0
  78. package/src/data-structures/queue/deque.ts +343 -68
  79. package/src/data-structures/queue/queue.ts +211 -42
  80. package/src/data-structures/stack/stack.ts +174 -32
  81. package/src/data-structures/trie/trie.ts +215 -44
  82. package/src/types/data-structures/binary-tree/segment-tree.ts +1 -1
  83. package/src/types/data-structures/linked-list/skip-linked-list.ts +2 -1
  84. package/src/types/data-structures/queue/deque.ts +7 -0
  85. package/src/utils/utils.ts +4 -2
@@ -8,6 +8,7 @@
8
8
 
9
9
  import type { Comparator, DFSOrderPattern, ElementCallback, HeapOptions } from '../../types';
10
10
  import { IterableElementBase } from '../base';
11
+ import { ERR } from '../../common';
11
12
 
12
13
  /**
13
14
  * Binary heap with pluggable comparator; supports fast insertion and removal of the top element.
@@ -25,105 +26,6 @@ import { IterableElementBase } from '../base';
25
26
  * 7. Efficient Sorting Algorithms: For example, heap sort. Heap sort uses the properties of a heap to sort elements.
26
27
  * 8. Graph Algorithms: Such as Dijkstra's shortest path algorithm and Prime's minimum-spanning tree algorithm, which use heaps to improve performance.
27
28
  * @example
28
- * // basic Heap creation and add operation
29
- * // Create a min heap (default)
30
- * const minHeap = new Heap([5, 3, 7, 1, 9, 2]);
31
- *
32
- * // Verify size
33
- * console.log(minHeap.size); // 6;
34
- *
35
- * // Add new element
36
- * minHeap.add(4);
37
- * console.log(minHeap.size); // 7;
38
- *
39
- * // Min heap property: smallest element at root
40
- * const min = minHeap.peek();
41
- * console.log(min); // 1;
42
- * @example
43
- * // Heap with custom comparator (MaxHeap behavior)
44
- * interface Task {
45
- * id: number;
46
- * priority: number;
47
- * name: string;
48
- * }
49
- *
50
- * // Custom comparator for max heap behavior (higher priority first)
51
- * const tasks: Task[] = [
52
- * { id: 1, priority: 5, name: 'Email' },
53
- * { id: 2, priority: 3, name: 'Chat' },
54
- * { id: 3, priority: 8, name: 'Alert' }
55
- * ];
56
- *
57
- * const maxHeap = new Heap(tasks, {
58
- * comparator: (a: Task, b: Task) => b.priority - a.priority
59
- * });
60
- *
61
- * console.log(maxHeap.size); // 3;
62
- *
63
- * // Peek returns highest priority task
64
- * const topTask = maxHeap.peek();
65
- * console.log(topTask?.priority); // 8;
66
- * console.log(topTask?.name); // 'Alert';
67
- * @example
68
- * // Heap for event processing with priority
69
- * interface Event {
70
- * id: number;
71
- * type: 'critical' | 'warning' | 'info';
72
- * timestamp: number;
73
- * message: string;
74
- * }
75
- *
76
- * // Custom priority: critical > warning > info
77
- * const priorityMap = { critical: 3, warning: 2, info: 1 };
78
- *
79
- * const eventHeap = new Heap<Event>([], {
80
- * comparator: (a: Event, b: Event) => {
81
- * const priorityA = priorityMap[a.type];
82
- * const priorityB = priorityMap[b.type];
83
- * return priorityB - priorityA; // Higher priority first
84
- * }
85
- * });
86
- *
87
- * // Add events in random order
88
- * eventHeap.add({ id: 1, type: 'info', timestamp: 100, message: 'User logged in' });
89
- * eventHeap.add({ id: 2, type: 'critical', timestamp: 101, message: 'Server down' });
90
- * eventHeap.add({ id: 3, type: 'warning', timestamp: 102, message: 'High memory' });
91
- * eventHeap.add({ id: 4, type: 'info', timestamp: 103, message: 'Cache cleared' });
92
- * eventHeap.add({ id: 5, type: 'critical', timestamp: 104, message: 'Database error' });
93
- *
94
- * console.log(eventHeap.size); // 5;
95
- *
96
- * // Process events by priority (critical first)
97
- * const processedOrder: Event[] = [];
98
- * while (eventHeap.size > 0) {
99
- * const event = eventHeap.poll();
100
- * if (event) {
101
- * processedOrder.push(event);
102
- * }
103
- * }
104
- *
105
- * // Verify critical events came first
106
- * console.log(processedOrder[0].type); // 'critical';
107
- * console.log(processedOrder[1].type); // 'critical';
108
- * console.log(processedOrder[2].type); // 'warning';
109
- * console.log(processedOrder[3].type); // 'info';
110
- * console.log(processedOrder[4].type); // 'info';
111
- *
112
- * // Verify O(log n) operations
113
- * const newHeap = new Heap<number>([5, 3, 7, 1]);
114
- *
115
- * // Add - O(log n)
116
- * newHeap.add(2);
117
- * console.log(newHeap.size); // 5;
118
- *
119
- * // Poll - O(log n)
120
- * const removed = newHeap.poll();
121
- * console.log(removed); // 1;
122
- *
123
- * // Peek - O(1)
124
- * const top = newHeap.peek();
125
- * console.log(top); // 2;
126
- * @example
127
29
  * // Use Heap to solve top k problems
128
30
  * function topKElements(arr: number[], k: number): number[] {
129
31
  * const heap = new Heap<number>([], { comparator: (a, b) => b - a }); // Max heap
@@ -238,6 +140,12 @@ import { IterableElementBase } from '../base';
238
140
  * ['Task5', 4]
239
141
  * ]);
240
142
  * console.log(scheduleTasks(tasks, 2)); // expectedMap;
143
+ * @example
144
+ * // Get all elements as array
145
+ * const heap = new Heap<number>([5, 1, 3, 2, 4]);
146
+ * const arr = heap.toArray();
147
+ * console.log(arr.length); // 5;
148
+ * console.log(arr.sort()); // [1, 2, 3, 4, 5];
241
149
  */
242
150
  export class Heap<E = any, R = any> extends IterableElementBase<E, R> {
243
151
  protected _equals: (a: E, b: E) => boolean = Object.is;
@@ -277,6 +185,26 @@ export class Heap<E = any, R = any> extends IterableElementBase<E, R> {
277
185
  * Get the number of elements.
278
186
  * @remarks Time O(1), Space O(1)
279
187
  * @returns Heap size.
188
+
189
+
190
+
191
+
192
+
193
+
194
+
195
+
196
+
197
+
198
+
199
+ * @example
200
+ * // Track heap capacity
201
+ * const heap = new Heap<number>();
202
+ * console.log(heap.size); // 0;
203
+ * heap.add(10);
204
+ * heap.add(20);
205
+ * console.log(heap.size); // 2;
206
+ * heap.poll();
207
+ * console.log(heap.size); // 1;
280
208
  */
281
209
 
282
210
  get size(): number {
@@ -331,6 +259,32 @@ export class Heap<E = any, R = any> extends IterableElementBase<E, R> {
331
259
  * @remarks Time O(1) amortized, Space O(1)
332
260
  * @param element - Element to insert.
333
261
  * @returns True.
262
+
263
+
264
+
265
+
266
+
267
+
268
+
269
+
270
+
271
+
272
+
273
+ * @example
274
+ * // basic Heap creation and add operation
275
+ * // Create a min heap (default)
276
+ * const minHeap = new Heap([5, 3, 7, 1, 9, 2]);
277
+ *
278
+ * // Verify size
279
+ * console.log(minHeap.size); // 6;
280
+ *
281
+ * // Add new element
282
+ * minHeap.add(4);
283
+ * console.log(minHeap.size); // 7;
284
+ *
285
+ * // Min heap property: smallest element at root
286
+ * const min = minHeap.peek();
287
+ * console.log(min); // 1;
334
288
  */
335
289
 
336
290
  add(element: E): boolean {
@@ -343,6 +297,20 @@ export class Heap<E = any, R = any> extends IterableElementBase<E, R> {
343
297
  * @remarks Time O(N log N), Space O(1)
344
298
  * @param elements - Iterable of elements or raw values.
345
299
  * @returns Array of per-element success flags.
300
+
301
+
302
+
303
+
304
+
305
+
306
+
307
+
308
+ * @example
309
+ * // Add multiple elements
310
+ * const heap = new Heap<number>([], { comparator: (a, b) => a - b });
311
+ * heap.addMany([5, 3, 7, 1]);
312
+ * console.log(heap.peek()); // 1;
313
+ * console.log(heap.size); // 4;
346
314
  */
347
315
 
348
316
  addMany(elements: Iterable<E | R>): boolean[] {
@@ -363,6 +331,42 @@ export class Heap<E = any, R = any> extends IterableElementBase<E, R> {
363
331
  * Remove and return the top element.
364
332
  * @remarks Time O(log N), Space O(1)
365
333
  * @returns Top element or undefined.
334
+
335
+
336
+
337
+
338
+
339
+
340
+
341
+
342
+
343
+
344
+
345
+ * @example
346
+ * // Heap with custom comparator (MaxHeap behavior)
347
+ * interface Task {
348
+ * id: number;
349
+ * priority: number;
350
+ * name: string;
351
+ * }
352
+ *
353
+ * // Custom comparator for max heap behavior (higher priority first)
354
+ * const tasks: Task[] = [
355
+ * { id: 1, priority: 5, name: 'Email' },
356
+ * { id: 2, priority: 3, name: 'Chat' },
357
+ * { id: 3, priority: 8, name: 'Alert' }
358
+ * ];
359
+ *
360
+ * const maxHeap = new Heap(tasks, {
361
+ * comparator: (a: Task, b: Task) => b.priority - a.priority
362
+ * });
363
+ *
364
+ * console.log(maxHeap.size); // 3;
365
+ *
366
+ * // Peek returns highest priority task
367
+ * const topTask = maxHeap.peek();
368
+ * console.log(topTask?.priority); // 8;
369
+ * console.log(topTask?.name); // 'Alert';
366
370
  */
367
371
 
368
372
  poll(): E | undefined {
@@ -380,6 +384,76 @@ export class Heap<E = any, R = any> extends IterableElementBase<E, R> {
380
384
  * Get the current top element without removing it.
381
385
  * @remarks Time O(1), Space O(1)
382
386
  * @returns Top element or undefined.
387
+
388
+
389
+
390
+
391
+
392
+
393
+
394
+
395
+
396
+
397
+
398
+ * @example
399
+ * // Heap for event processing with priority
400
+ * interface Event {
401
+ * id: number;
402
+ * type: 'critical' | 'warning' | 'info';
403
+ * timestamp: number;
404
+ * message: string;
405
+ * }
406
+ *
407
+ * // Custom priority: critical > warning > info
408
+ * const priorityMap = { critical: 3, warning: 2, info: 1 };
409
+ *
410
+ * const eventHeap = new Heap<Event>([], {
411
+ * comparator: (a: Event, b: Event) => {
412
+ * const priorityA = priorityMap[a.type];
413
+ * const priorityB = priorityMap[b.type];
414
+ * return priorityB - priorityA; // Higher priority first
415
+ * }
416
+ * });
417
+ *
418
+ * // Add events in random order
419
+ * eventHeap.add({ id: 1, type: 'info', timestamp: 100, message: 'User logged in' });
420
+ * eventHeap.add({ id: 2, type: 'critical', timestamp: 101, message: 'Server down' });
421
+ * eventHeap.add({ id: 3, type: 'warning', timestamp: 102, message: 'High memory' });
422
+ * eventHeap.add({ id: 4, type: 'info', timestamp: 103, message: 'Cache cleared' });
423
+ * eventHeap.add({ id: 5, type: 'critical', timestamp: 104, message: 'Database error' });
424
+ *
425
+ * console.log(eventHeap.size); // 5;
426
+ *
427
+ * // Process events by priority (critical first)
428
+ * const processedOrder: Event[] = [];
429
+ * while (eventHeap.size > 0) {
430
+ * const event = eventHeap.poll();
431
+ * if (event) {
432
+ * processedOrder.push(event);
433
+ * }
434
+ * }
435
+ *
436
+ * // Verify critical events came first
437
+ * console.log(processedOrder[0].type); // 'critical';
438
+ * console.log(processedOrder[1].type); // 'critical';
439
+ * console.log(processedOrder[2].type); // 'warning';
440
+ * console.log(processedOrder[3].type); // 'info';
441
+ * console.log(processedOrder[4].type); // 'info';
442
+ *
443
+ * // Verify O(log n) operations
444
+ * const newHeap = new Heap<number>([5, 3, 7, 1]);
445
+ *
446
+ * // Add - O(log n)
447
+ * newHeap.add(2);
448
+ * console.log(newHeap.size); // 5;
449
+ *
450
+ * // Poll - O(log n)
451
+ * const removed = newHeap.poll();
452
+ * console.log(removed); // 1;
453
+ *
454
+ * // Peek - O(1)
455
+ * const top = newHeap.peek();
456
+ * console.log(top); // 2;
383
457
  */
384
458
 
385
459
  peek(): E | undefined {
@@ -390,6 +464,21 @@ export class Heap<E = any, R = any> extends IterableElementBase<E, R> {
390
464
  * Check whether the heap is empty.
391
465
  * @remarks Time O(1), Space O(1)
392
466
  * @returns True if size is 0.
467
+
468
+
469
+
470
+
471
+
472
+
473
+
474
+
475
+
476
+ * @example
477
+ * // Check if heap is empty
478
+ * const heap = new Heap<number>([], { comparator: (a, b) => a - b });
479
+ * console.log(heap.isEmpty()); // true;
480
+ * heap.add(1);
481
+ * console.log(heap.isEmpty()); // false;
393
482
  */
394
483
 
395
484
  isEmpty(): boolean {
@@ -400,6 +489,20 @@ export class Heap<E = any, R = any> extends IterableElementBase<E, R> {
400
489
  * Remove all elements.
401
490
  * @remarks Time O(1), Space O(1)
402
491
  * @returns void
492
+
493
+
494
+
495
+
496
+
497
+
498
+
499
+
500
+
501
+ * @example
502
+ * // Remove all elements
503
+ * const heap = new Heap<number>([1, 2, 3], { comparator: (a, b) => a - b });
504
+ * heap.clear();
505
+ * console.log(heap.isEmpty()); // true;
403
506
  */
404
507
 
405
508
  clear(): void {
@@ -423,6 +526,13 @@ export class Heap<E = any, R = any> extends IterableElementBase<E, R> {
423
526
  * @remarks Time O(N), Space O(1)
424
527
  * @param element - Element to search for.
425
528
  * @returns True if found.
529
+
530
+
531
+ * @example
532
+ * // Check element existence
533
+ * const heap = new Heap<number>([3, 1, 2], { comparator: (a, b) => a - b });
534
+ * console.log(heap.has(1)); // true;
535
+ * console.log(heap.has(99)); // false;
426
536
  */
427
537
 
428
538
  override has(element: E): boolean {
@@ -435,6 +545,19 @@ export class Heap<E = any, R = any> extends IterableElementBase<E, R> {
435
545
  * @remarks Time O(N), Space O(1)
436
546
  * @param element - Element to delete.
437
547
  * @returns True if an element was removed.
548
+
549
+
550
+
551
+
552
+
553
+
554
+
555
+
556
+ * @example
557
+ * // Remove specific element
558
+ * const heap = new Heap<number>([3, 1, 4, 1, 5], { comparator: (a, b) => a - b });
559
+ * heap.delete(4);
560
+ * console.log(heap.toArray().includes(4)); // false;
438
561
  */
439
562
 
440
563
  delete(element: E): boolean {
@@ -503,6 +626,13 @@ export class Heap<E = any, R = any> extends IterableElementBase<E, R> {
503
626
  * @remarks Time O(N), Space O(H)
504
627
  * @param [order] - Traversal order: 'PRE' | 'IN' | 'POST'.
505
628
  * @returns Array of visited elements.
629
+
630
+
631
+ * @example
632
+ * // Depth-first traversal
633
+ * const heap = new Heap<number>([3, 1, 2], { comparator: (a, b) => a - b });
634
+ * const result = heap.dfs('IN');
635
+ * console.log(result.length); // 3;
506
636
  */
507
637
 
508
638
  dfs(order: DFSOrderPattern = 'PRE'): E[] {
@@ -548,6 +678,22 @@ export class Heap<E = any, R = any> extends IterableElementBase<E, R> {
548
678
  * Return all elements in ascending order by repeatedly polling.
549
679
  * @remarks Time O(N log N), Space O(N)
550
680
  * @returns Sorted array of elements.
681
+
682
+
683
+
684
+
685
+
686
+
687
+
688
+
689
+
690
+
691
+
692
+ * @example
693
+ * // Sort elements using heap
694
+ * const heap = new Heap<number>([5, 1, 3, 2, 4]);
695
+ * const sorted = heap.sort();
696
+ * console.log(sorted); // [1, 2, 3, 4, 5];
551
697
  */
552
698
 
553
699
  sort(): E[] {
@@ -565,6 +711,22 @@ export class Heap<E = any, R = any> extends IterableElementBase<E, R> {
565
711
  * Deep clone this heap.
566
712
  * @remarks Time O(N), Space O(N)
567
713
  * @returns A new heap with the same elements.
714
+
715
+
716
+
717
+
718
+
719
+
720
+
721
+
722
+
723
+ * @example
724
+ * // Create independent copy
725
+ * const heap = new Heap<number>([3, 1, 4], { comparator: (a, b) => a - b });
726
+ * const copy = heap.clone();
727
+ * copy.poll();
728
+ * console.log(heap.size); // 3;
729
+ * console.log(copy.size); // 2;
568
730
  */
569
731
 
570
732
  clone(): this {
@@ -579,6 +741,20 @@ export class Heap<E = any, R = any> extends IterableElementBase<E, R> {
579
741
  * @param callback - Predicate (element, index, heap) → boolean to keep element.
580
742
  * @param [thisArg] - Value for `this` inside the callback.
581
743
  * @returns A new heap with the kept elements.
744
+
745
+
746
+
747
+
748
+
749
+
750
+
751
+
752
+
753
+ * @example
754
+ * // Filter elements
755
+ * const heap = new Heap<number>([1, 2, 3, 4, 5], { comparator: (a, b) => a - b });
756
+ * const evens = heap.filter(x => x % 2 === 0);
757
+ * console.log(evens.size); // 2;
582
758
  */
583
759
 
584
760
  filter(callback: ElementCallback<E, R, boolean>, thisArg?: unknown): this {
@@ -603,6 +779,19 @@ export class Heap<E = any, R = any> extends IterableElementBase<E, R> {
603
779
  * @param options - Options for the output heap, including comparator for EM.
604
780
  * @param [thisArg] - Value for `this` inside the callback.
605
781
  * @returns A new heap with mapped elements.
782
+
783
+
784
+
785
+
786
+
787
+
788
+
789
+
790
+ * @example
791
+ * // Transform elements
792
+ * const heap = new Heap<number>([1, 2, 3], { comparator: (a, b) => a - b });
793
+ * const doubled = heap.map(x => x * 2, { comparator: (a, b) => a - b });
794
+ * console.log(doubled.peek()); // 2;
606
795
  */
607
796
 
608
797
  map<EM, RM>(
@@ -611,7 +800,7 @@ export class Heap<E = any, R = any> extends IterableElementBase<E, R> {
611
800
  thisArg?: unknown
612
801
  ): Heap<EM, RM> {
613
802
  const { comparator, toElementFn, ...rest } = options ?? {};
614
- if (!comparator) throw new TypeError('Heap.map requires options.comparator for EM');
803
+ if (!comparator) throw new TypeError(ERR.comparatorRequired('Heap.map'));
615
804
  const out = this._createLike<EM, RM>([], { ...rest, comparator, toElementFn });
616
805
  let i = 0;
617
806
  for (const x of this) {
@@ -641,7 +830,7 @@ export class Heap<E = any, R = any> extends IterableElementBase<E, R> {
641
830
 
642
831
  protected readonly _DEFAULT_COMPARATOR: Comparator<E> = (a: E, b: E): number => {
643
832
  if (typeof a === 'object' || typeof b === 'object') {
644
- throw TypeError('When comparing object types, define a custom comparator in options.');
833
+ throw new TypeError(ERR.comparatorRequired('Heap'));
645
834
  }
646
835
  if (a > b) return 1;
647
836
  if (a < b) return -1;
@@ -783,7 +972,7 @@ export class FibonacciHeap<E> {
783
972
  constructor(comparator?: Comparator<E>) {
784
973
  this.clear();
785
974
  this._comparator = comparator || this._defaultComparator;
786
- if (typeof this.comparator !== 'function') throw new Error('FibonacciHeap: comparator must be a function.');
975
+ if (typeof this.comparator !== 'function') throw new TypeError(ERR.notAFunction('comparator', 'FibonacciHeap'));
787
976
  }
788
977
 
789
978
  protected _root?: FibonacciHeapNode<E>;
@@ -6,6 +6,7 @@
6
6
  */
7
7
  import type { HeapOptions } from '../../types';
8
8
  import { Heap } from './heap';
9
+ import { ERR } from '../../common';
9
10
 
10
11
  /**
11
12
  * @template E
@@ -22,6 +23,52 @@ import { Heap } from './heap';
22
23
  * 7. Efficient Sorting Algorithms: For example, heap sort. Heap sort uses the properties of a heap to sort elements.
23
24
  * 8. Graph Algorithms: Such as Dijkstra's shortest path algorithm and Prim's minimum-spanning tree algorithm, which use heaps to improve performance.
24
25
  * @example
26
+ * // Find the K largest elements
27
+ * const data = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
28
+ * const heap = new MaxHeap(data);
29
+ *
30
+ * // Extract top 3 elements
31
+ * const top3 = [];
32
+ * for (let i = 0; i < 3; i++) {
33
+ * top3.push(heap.poll());
34
+ * }
35
+ * console.log(top3); // [9, 6, 5];
36
+ * @example
37
+ * // Priority-based task processing
38
+ * interface Task {
39
+ * name: string;
40
+ * priority: number;
41
+ * }
42
+ *
43
+ * const heap = new MaxHeap<Task>([], {
44
+ * comparator: (a, b) => b.priority - a.priority
45
+ * });
46
+ *
47
+ * heap.add({ name: 'Low priority', priority: 1 });
48
+ * heap.add({ name: 'Critical fix', priority: 10 });
49
+ * heap.add({ name: 'Medium task', priority: 5 });
50
+ *
51
+ * // Highest priority first
52
+ * console.log(heap.poll()?.name); // 'Critical fix';
53
+ * console.log(heap.poll()?.name); // 'Medium task';
54
+ * console.log(heap.poll()?.name); // 'Low priority';
55
+ * @example
56
+ * // Real-time top score tracking
57
+ * const scores = new MaxHeap<number>();
58
+ *
59
+ * // Stream of scores coming in
60
+ * for (const score of [72, 85, 91, 68, 95, 78, 88]) {
61
+ * scores.add(score);
62
+ * }
63
+ *
64
+ * // Current highest score without removing
65
+ * console.log(scores.peek()); // 95;
66
+ * console.log(scores.size); // 7;
67
+ *
68
+ * // Remove top 2 scores
69
+ * console.log(scores.poll()); // 95;
70
+ * console.log(scores.poll()); // 91;
71
+ * console.log(scores.peek()); // 88;
25
72
  */
26
73
  export class MaxHeap<E = any, R = any> extends Heap<E, R> {
27
74
  /**
@@ -33,9 +80,7 @@ export class MaxHeap<E = any, R = any> extends Heap<E, R> {
33
80
  super(elements, {
34
81
  comparator: (a: E, b: E): number => {
35
82
  if (typeof a === 'object' || typeof b === 'object') {
36
- throw TypeError(
37
- `When comparing object types, a custom comparator must be defined in the constructor's options parameter.`
38
- );
83
+ throw new TypeError(ERR.comparatorRequired('MaxHeap'));
39
84
  }
40
85
  if (a < b) return 1;
41
86
  if (a > b) return -1;
@@ -23,6 +23,65 @@ import { Heap } from './heap';
23
23
  * 7. Efficient Sorting Algorithms: For example, heap sort. MinHeap sort uses the properties of a heap to sort elements.
24
24
  * 8. Graph Algorithms: Such as Dijkstra's shortest path algorithm and Prim's minimum spanning tree algorithm, which use heaps to improve performance.
25
25
  * @example
26
+ * // Merge K sorted arrays
27
+ * const arrays = [
28
+ * [1, 4, 7],
29
+ * [2, 5, 8],
30
+ * [3, 6, 9]
31
+ * ];
32
+ *
33
+ * // Use min heap to merge: track (value, arrayIndex, elementIndex)
34
+ * const heap = new MinHeap<[number, number, number]>([], {
35
+ * comparator: (a, b) => a[0] - b[0]
36
+ * });
37
+ *
38
+ * // Initialize with first element of each array
39
+ * arrays.forEach((arr, i) => heap.add([arr[0], i, 0]));
40
+ *
41
+ * const merged: number[] = [];
42
+ * while (heap.size > 0) {
43
+ * const [val, arrIdx, elemIdx] = heap.poll()!;
44
+ * merged.push(val);
45
+ * if (elemIdx + 1 < arrays[arrIdx].length) {
46
+ * heap.add([arrays[arrIdx][elemIdx + 1], arrIdx, elemIdx + 1]);
47
+ * }
48
+ * }
49
+ *
50
+ * console.log(merged); // [1, 2, 3, 4, 5, 6, 7, 8, 9];
51
+ * @example
52
+ * // Dijkstra-style shortest distance tracking
53
+ * // Simulating distance updates: (distance, nodeId)
54
+ * const heap = new MinHeap<[number, string]>([], {
55
+ * comparator: (a, b) => a[0] - b[0]
56
+ * });
57
+ *
58
+ * heap.add([0, 'start']);
59
+ * heap.add([10, 'A']);
60
+ * heap.add([5, 'B']);
61
+ * heap.add([3, 'C']);
62
+ *
63
+ * // Process nearest node first
64
+ * console.log(heap.poll()); // [0, 'start'];
65
+ * console.log(heap.poll()); // [3, 'C'];
66
+ * console.log(heap.poll()); // [5, 'B'];
67
+ * console.log(heap.poll()); // [10, 'A'];
68
+ * @example
69
+ * // Running median with min heap (upper half)
70
+ * const upperHalf = new MinHeap<number>();
71
+ *
72
+ * // Add larger numbers to min heap
73
+ * for (const n of [5, 8, 3, 9, 1]) {
74
+ * upperHalf.add(n);
75
+ * }
76
+ *
77
+ * // Smallest of the upper half is always accessible
78
+ * console.log(upperHalf.peek()); // 1;
79
+ * console.log(upperHalf.size); // 5;
80
+ *
81
+ * // Remove smallest repeatedly
82
+ * console.log(upperHalf.poll()); // 1;
83
+ * console.log(upperHalf.poll()); // 3;
84
+ * console.log(upperHalf.peek()); // 5;
26
85
  */
27
86
  export class MinHeap<E = any, R = any> extends Heap<E, R> {
28
87
  /**