avl-tree-typed 2.4.5 → 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 (75) hide show
  1. package/dist/cjs/index.cjs +1287 -570
  2. package/dist/cjs/index.cjs.map +1 -1
  3. package/dist/cjs-legacy/index.cjs +1314 -597
  4. package/dist/cjs-legacy/index.cjs.map +1 -1
  5. package/dist/esm/index.mjs +1287 -570
  6. package/dist/esm/index.mjs.map +1 -1
  7. package/dist/esm-legacy/index.mjs +1314 -597
  8. package/dist/esm-legacy/index.mjs.map +1 -1
  9. package/dist/types/data-structures/base/iterable-element-base.d.ts +1 -1
  10. package/dist/types/data-structures/binary-tree/avl-tree.d.ts +128 -51
  11. package/dist/types/data-structures/binary-tree/binary-indexed-tree.d.ts +210 -164
  12. package/dist/types/data-structures/binary-tree/binary-tree.d.ts +429 -78
  13. package/dist/types/data-structures/binary-tree/bst.d.ts +311 -28
  14. package/dist/types/data-structures/binary-tree/red-black-tree.d.ts +212 -32
  15. package/dist/types/data-structures/binary-tree/segment-tree.d.ts +218 -152
  16. package/dist/types/data-structures/binary-tree/tree-map.d.ts +1281 -5
  17. package/dist/types/data-structures/binary-tree/tree-multi-map.d.ts +1087 -201
  18. package/dist/types/data-structures/binary-tree/tree-multi-set.d.ts +858 -65
  19. package/dist/types/data-structures/binary-tree/tree-set.d.ts +1133 -5
  20. package/dist/types/data-structures/graph/directed-graph.d.ts +219 -47
  21. package/dist/types/data-structures/graph/map-graph.d.ts +59 -1
  22. package/dist/types/data-structures/graph/undirected-graph.d.ts +204 -59
  23. package/dist/types/data-structures/hash/hash-map.d.ts +230 -77
  24. package/dist/types/data-structures/heap/heap.d.ts +287 -99
  25. package/dist/types/data-structures/heap/max-heap.d.ts +46 -0
  26. package/dist/types/data-structures/heap/min-heap.d.ts +59 -0
  27. package/dist/types/data-structures/linked-list/doubly-linked-list.d.ts +286 -44
  28. package/dist/types/data-structures/linked-list/singly-linked-list.d.ts +278 -65
  29. package/dist/types/data-structures/linked-list/skip-linked-list.d.ts +415 -12
  30. package/dist/types/data-structures/matrix/matrix.d.ts +331 -0
  31. package/dist/types/data-structures/priority-queue/max-priority-queue.d.ts +57 -0
  32. package/dist/types/data-structures/priority-queue/min-priority-queue.d.ts +60 -0
  33. package/dist/types/data-structures/priority-queue/priority-queue.d.ts +60 -0
  34. package/dist/types/data-structures/queue/deque.d.ts +272 -65
  35. package/dist/types/data-structures/queue/queue.d.ts +211 -42
  36. package/dist/types/data-structures/stack/stack.d.ts +174 -32
  37. package/dist/types/data-structures/trie/trie.d.ts +213 -43
  38. package/dist/types/types/data-structures/binary-tree/segment-tree.d.ts +1 -1
  39. package/dist/types/types/data-structures/linked-list/skip-linked-list.d.ts +1 -4
  40. package/dist/umd/avl-tree-typed.js +1315 -598
  41. package/dist/umd/avl-tree-typed.js.map +1 -1
  42. package/dist/umd/avl-tree-typed.min.js +2 -2
  43. package/dist/umd/avl-tree-typed.min.js.map +1 -1
  44. package/package.json +2 -2
  45. package/src/data-structures/base/iterable-element-base.ts +4 -5
  46. package/src/data-structures/binary-tree/avl-tree.ts +134 -51
  47. package/src/data-structures/binary-tree/binary-indexed-tree.ts +302 -247
  48. package/src/data-structures/binary-tree/binary-tree.ts +429 -79
  49. package/src/data-structures/binary-tree/bst.ts +335 -34
  50. package/src/data-structures/binary-tree/red-black-tree.ts +290 -97
  51. package/src/data-structures/binary-tree/segment-tree.ts +372 -248
  52. package/src/data-structures/binary-tree/tree-map.ts +1284 -6
  53. package/src/data-structures/binary-tree/tree-multi-map.ts +1094 -211
  54. package/src/data-structures/binary-tree/tree-multi-set.ts +858 -65
  55. package/src/data-structures/binary-tree/tree-set.ts +1136 -9
  56. package/src/data-structures/graph/directed-graph.ts +219 -47
  57. package/src/data-structures/graph/map-graph.ts +59 -1
  58. package/src/data-structures/graph/undirected-graph.ts +204 -59
  59. package/src/data-structures/hash/hash-map.ts +230 -77
  60. package/src/data-structures/heap/heap.ts +287 -99
  61. package/src/data-structures/heap/max-heap.ts +46 -0
  62. package/src/data-structures/heap/min-heap.ts +59 -0
  63. package/src/data-structures/linked-list/doubly-linked-list.ts +286 -44
  64. package/src/data-structures/linked-list/singly-linked-list.ts +278 -65
  65. package/src/data-structures/linked-list/skip-linked-list.ts +689 -90
  66. package/src/data-structures/matrix/matrix.ts +416 -12
  67. package/src/data-structures/priority-queue/max-priority-queue.ts +57 -0
  68. package/src/data-structures/priority-queue/min-priority-queue.ts +60 -0
  69. package/src/data-structures/priority-queue/priority-queue.ts +60 -0
  70. package/src/data-structures/queue/deque.ts +272 -65
  71. package/src/data-structures/queue/queue.ts +211 -42
  72. package/src/data-structures/stack/stack.ts +174 -32
  73. package/src/data-structures/trie/trie.ts +213 -43
  74. package/src/types/data-structures/binary-tree/segment-tree.ts +1 -1
  75. package/src/types/data-structures/linked-list/skip-linked-list.ts +2 -1
@@ -59,50 +59,6 @@ function makeTrampoline(fn) {
59
59
  }
60
60
  __name(makeTrampoline, "makeTrampoline");
61
61
 
62
- // src/common/error.ts
63
- var ERR = {
64
- // Range / index
65
- indexOutOfRange: /* @__PURE__ */ __name((index, min, max, ctx) => `${ctx ? ctx + ": " : ""}Index ${index} is out of range [${min}, ${max}].`, "indexOutOfRange"),
66
- invalidIndex: /* @__PURE__ */ __name((ctx) => `${ctx ? ctx + ": " : ""}Index must be an integer.`, "invalidIndex"),
67
- // Type / argument
68
- invalidArgument: /* @__PURE__ */ __name((reason, ctx) => `${ctx ? ctx + ": " : ""}${reason}`, "invalidArgument"),
69
- comparatorRequired: /* @__PURE__ */ __name((ctx) => `${ctx ? ctx + ": " : ""}Comparator is required for non-number/non-string/non-Date keys.`, "comparatorRequired"),
70
- invalidKey: /* @__PURE__ */ __name((reason, ctx) => `${ctx ? ctx + ": " : ""}${reason}`, "invalidKey"),
71
- notAFunction: /* @__PURE__ */ __name((name, ctx) => `${ctx ? ctx + ": " : ""}${name} must be a function.`, "notAFunction"),
72
- invalidEntry: /* @__PURE__ */ __name((ctx) => `${ctx ? ctx + ": " : ""}Each entry must be a [key, value] tuple.`, "invalidEntry"),
73
- invalidNaN: /* @__PURE__ */ __name((ctx) => `${ctx ? ctx + ": " : ""}NaN is not a valid key.`, "invalidNaN"),
74
- invalidDate: /* @__PURE__ */ __name((ctx) => `${ctx ? ctx + ": " : ""}Invalid Date key.`, "invalidDate"),
75
- reduceEmpty: /* @__PURE__ */ __name((ctx) => `${ctx ? ctx + ": " : ""}Reduce of empty structure with no initial value.`, "reduceEmpty"),
76
- callbackReturnType: /* @__PURE__ */ __name((expected, got, ctx) => `${ctx ? ctx + ": " : ""}Callback must return ${expected}; got ${got}.`, "callbackReturnType"),
77
- // State / operation
78
- invalidOperation: /* @__PURE__ */ __name((reason, ctx) => `${ctx ? ctx + ": " : ""}${reason}`, "invalidOperation"),
79
- // Matrix
80
- matrixDimensionMismatch: /* @__PURE__ */ __name((op) => `Matrix: Dimensions must be compatible for ${op}.`, "matrixDimensionMismatch"),
81
- matrixSingular: /* @__PURE__ */ __name(() => "Matrix: Singular matrix, inverse does not exist.", "matrixSingular"),
82
- matrixNotSquare: /* @__PURE__ */ __name(() => "Matrix: Must be square for inversion.", "matrixNotSquare"),
83
- matrixNotRectangular: /* @__PURE__ */ __name(() => "Matrix: Must be rectangular for transposition.", "matrixNotRectangular"),
84
- matrixRowMismatch: /* @__PURE__ */ __name((expected, got) => `Matrix: Expected row length ${expected}, but got ${got}.`, "matrixRowMismatch")
85
- };
86
-
87
- // src/common/index.ts
88
- var Range = class {
89
- constructor(low, high, includeLow = true, includeHigh = true) {
90
- this.low = low;
91
- this.high = high;
92
- this.includeLow = includeLow;
93
- this.includeHigh = includeHigh;
94
- }
95
- static {
96
- __name(this, "Range");
97
- }
98
- // Determine whether a key is within the range
99
- isInRange(key, comparator) {
100
- const lowCheck = this.includeLow ? comparator(key, this.low) >= 0 : comparator(key, this.low) > 0;
101
- const highCheck = this.includeHigh ? comparator(key, this.high) <= 0 : comparator(key, this.high) < 0;
102
- return lowCheck && highCheck;
103
- }
104
- };
105
-
106
62
  // src/data-structures/base/iterable-element-base.ts
107
63
  var IterableElementBase = class {
108
64
  static {
@@ -121,7 +77,7 @@ var IterableElementBase = class {
121
77
  if (options) {
122
78
  const { toElementFn } = options;
123
79
  if (typeof toElementFn === "function") this._toElementFn = toElementFn;
124
- else if (toElementFn) throw new TypeError(ERR.notAFunction("toElementFn"));
80
+ else if (toElementFn) throw new TypeError("toElementFn must be a function type");
125
81
  }
126
82
  }
127
83
  /**
@@ -284,7 +240,7 @@ var IterableElementBase = class {
284
240
  acc = initialValue;
285
241
  } else {
286
242
  const first = iter.next();
287
- if (first.done) throw new TypeError(ERR.reduceEmpty());
243
+ if (first.done) throw new TypeError("Reduce of empty structure with no initial value");
288
244
  acc = first.value;
289
245
  index = 1;
290
246
  }
@@ -519,6 +475,232 @@ var LinearBase = class _LinearBase extends IterableElementBase {
519
475
  }
520
476
  };
521
477
 
478
+ // src/common/error.ts
479
+ var ERR = {
480
+ // Range / index
481
+ indexOutOfRange: /* @__PURE__ */ __name((index, min, max, ctx) => `${ctx ? ctx + ": " : ""}Index ${index} is out of range [${min}, ${max}].`, "indexOutOfRange"),
482
+ invalidIndex: /* @__PURE__ */ __name((ctx) => `${ctx ? ctx + ": " : ""}Index must be an integer.`, "invalidIndex"),
483
+ // Type / argument
484
+ invalidArgument: /* @__PURE__ */ __name((reason, ctx) => `${ctx ? ctx + ": " : ""}${reason}`, "invalidArgument"),
485
+ comparatorRequired: /* @__PURE__ */ __name((ctx) => `${ctx ? ctx + ": " : ""}Comparator is required for non-number/non-string/non-Date keys.`, "comparatorRequired"),
486
+ invalidKey: /* @__PURE__ */ __name((reason, ctx) => `${ctx ? ctx + ": " : ""}${reason}`, "invalidKey"),
487
+ notAFunction: /* @__PURE__ */ __name((name, ctx) => `${ctx ? ctx + ": " : ""}${name} must be a function.`, "notAFunction"),
488
+ invalidEntry: /* @__PURE__ */ __name((ctx) => `${ctx ? ctx + ": " : ""}Each entry must be a [key, value] tuple.`, "invalidEntry"),
489
+ invalidNaN: /* @__PURE__ */ __name((ctx) => `${ctx ? ctx + ": " : ""}NaN is not a valid key.`, "invalidNaN"),
490
+ invalidDate: /* @__PURE__ */ __name((ctx) => `${ctx ? ctx + ": " : ""}Invalid Date key.`, "invalidDate"),
491
+ reduceEmpty: /* @__PURE__ */ __name((ctx) => `${ctx ? ctx + ": " : ""}Reduce of empty structure with no initial value.`, "reduceEmpty"),
492
+ callbackReturnType: /* @__PURE__ */ __name((expected, got, ctx) => `${ctx ? ctx + ": " : ""}Callback must return ${expected}; got ${got}.`, "callbackReturnType"),
493
+ // State / operation
494
+ invalidOperation: /* @__PURE__ */ __name((reason, ctx) => `${ctx ? ctx + ": " : ""}${reason}`, "invalidOperation"),
495
+ // Matrix
496
+ matrixDimensionMismatch: /* @__PURE__ */ __name((op) => `Matrix: Dimensions must be compatible for ${op}.`, "matrixDimensionMismatch"),
497
+ matrixSingular: /* @__PURE__ */ __name(() => "Matrix: Singular matrix, inverse does not exist.", "matrixSingular"),
498
+ matrixNotSquare: /* @__PURE__ */ __name(() => "Matrix: Must be square for inversion.", "matrixNotSquare"),
499
+ matrixNotRectangular: /* @__PURE__ */ __name(() => "Matrix: Must be rectangular for transposition.", "matrixNotRectangular"),
500
+ matrixRowMismatch: /* @__PURE__ */ __name((expected, got) => `Matrix: Expected row length ${expected}, but got ${got}.`, "matrixRowMismatch")
501
+ };
502
+
503
+ // src/common/index.ts
504
+ var Range = class {
505
+ constructor(low, high, includeLow = true, includeHigh = true) {
506
+ this.low = low;
507
+ this.high = high;
508
+ this.includeLow = includeLow;
509
+ this.includeHigh = includeHigh;
510
+ }
511
+ static {
512
+ __name(this, "Range");
513
+ }
514
+ // Determine whether a key is within the range
515
+ isInRange(key, comparator) {
516
+ const lowCheck = this.includeLow ? comparator(key, this.low) >= 0 : comparator(key, this.low) > 0;
517
+ const highCheck = this.includeHigh ? comparator(key, this.high) <= 0 : comparator(key, this.high) < 0;
518
+ return lowCheck && highCheck;
519
+ }
520
+ };
521
+
522
+ // src/data-structures/base/iterable-entry-base.ts
523
+ var IterableEntryBase = class {
524
+ static {
525
+ __name(this, "IterableEntryBase");
526
+ }
527
+ /**
528
+ * Default iterator yielding `[key, value]` entries.
529
+ * @returns Iterator of `[K, V]`.
530
+ * @remarks Time O(n) to iterate, Space O(1)
531
+ */
532
+ *[Symbol.iterator](...args) {
533
+ yield* this._getIterator(...args);
534
+ }
535
+ /**
536
+ * Iterate over `[key, value]` pairs (may yield `undefined` values).
537
+ * @returns Iterator of `[K, V | undefined]`.
538
+ * @remarks Time O(n), Space O(1)
539
+ */
540
+ *entries() {
541
+ for (const item of this) {
542
+ yield item;
543
+ }
544
+ }
545
+ /**
546
+ * Iterate over keys only.
547
+ * @returns Iterator of keys.
548
+ * @remarks Time O(n), Space O(1)
549
+ */
550
+ *keys() {
551
+ for (const item of this) {
552
+ yield item[0];
553
+ }
554
+ }
555
+ /**
556
+ * Iterate over values only.
557
+ * @returns Iterator of values.
558
+ * @remarks Time O(n), Space O(1)
559
+ */
560
+ *values() {
561
+ for (const item of this) {
562
+ yield item[1];
563
+ }
564
+ }
565
+ /**
566
+ * Test whether all entries satisfy the predicate.
567
+ * @param predicate - `(key, value, index, self) => boolean`.
568
+ * @param thisArg - Optional `this` for callback.
569
+ * @returns `true` if all pass; otherwise `false`.
570
+ * @remarks Time O(n), Space O(1)
571
+ */
572
+ every(predicate, thisArg) {
573
+ let index = 0;
574
+ for (const item of this) {
575
+ if (!predicate.call(thisArg, item[1], item[0], index++, this)) {
576
+ return false;
577
+ }
578
+ }
579
+ return true;
580
+ }
581
+ /**
582
+ * Test whether any entry satisfies the predicate.
583
+ * @param predicate - `(key, value, index, self) => boolean`.
584
+ * @param thisArg - Optional `this` for callback.
585
+ * @returns `true` if any passes; otherwise `false`.
586
+ * @remarks Time O(n), Space O(1)
587
+ */
588
+ some(predicate, thisArg) {
589
+ let index = 0;
590
+ for (const item of this) {
591
+ if (predicate.call(thisArg, item[1], item[0], index++, this)) {
592
+ return true;
593
+ }
594
+ }
595
+ return false;
596
+ }
597
+ /**
598
+ * Visit each entry, left-to-right.
599
+ * @param callbackfn - `(key, value, index, self) => void`.
600
+ * @param thisArg - Optional `this` for callback.
601
+ * @remarks Time O(n), Space O(1)
602
+ */
603
+ forEach(callbackfn, thisArg) {
604
+ let index = 0;
605
+ for (const item of this) {
606
+ const [key, value] = item;
607
+ callbackfn.call(thisArg, value, key, index++, this);
608
+ }
609
+ }
610
+ /**
611
+ * Find the first entry that matches a predicate.
612
+ * @param callbackfn - `(key, value, index, self) => boolean`.
613
+ * @param thisArg - Optional `this` for callback.
614
+ * @returns Matching `[key, value]` or `undefined`.
615
+ * @remarks Time O(n), Space O(1)
616
+ */
617
+ find(callbackfn, thisArg) {
618
+ let index = 0;
619
+ for (const item of this) {
620
+ const [key, value] = item;
621
+ if (callbackfn.call(thisArg, value, key, index++, this)) return item;
622
+ }
623
+ return;
624
+ }
625
+ /**
626
+ * Whether the given key exists.
627
+ * @param key - Key to test.
628
+ * @returns `true` if found; otherwise `false`.
629
+ * @remarks Time O(n) generic, Space O(1)
630
+ */
631
+ has(key) {
632
+ for (const item of this) {
633
+ const [itemKey] = item;
634
+ if (itemKey === key) return true;
635
+ }
636
+ return false;
637
+ }
638
+ /**
639
+ * Whether there exists an entry with the given value.
640
+ * @param value - Value to test.
641
+ * @returns `true` if found; otherwise `false`.
642
+ * @remarks Time O(n), Space O(1)
643
+ */
644
+ hasValue(value) {
645
+ for (const [, elementValue] of this) {
646
+ if (elementValue === value) return true;
647
+ }
648
+ return false;
649
+ }
650
+ /**
651
+ * Get the value under a key.
652
+ * @param key - Key to look up.
653
+ * @returns Value or `undefined`.
654
+ * @remarks Time O(n) generic, Space O(1)
655
+ */
656
+ get(key) {
657
+ for (const item of this) {
658
+ const [itemKey, value] = item;
659
+ if (itemKey === key) return value;
660
+ }
661
+ return;
662
+ }
663
+ /**
664
+ * Reduce entries into a single accumulator.
665
+ * @param callbackfn - `(acc, value, key, index, self) => acc`.
666
+ * @param initialValue - Initial accumulator.
667
+ * @returns Final accumulator.
668
+ * @remarks Time O(n), Space O(1)
669
+ */
670
+ reduce(callbackfn, initialValue) {
671
+ let accumulator = initialValue;
672
+ let index = 0;
673
+ for (const item of this) {
674
+ const [key, value] = item;
675
+ accumulator = callbackfn(accumulator, value, key, index++, this);
676
+ }
677
+ return accumulator;
678
+ }
679
+ /**
680
+ * Converts data structure to `[key, value]` pairs.
681
+ * @returns Array of entries.
682
+ * @remarks Time O(n), Space O(n)
683
+ */
684
+ toArray() {
685
+ return [...this];
686
+ }
687
+ /**
688
+ * Visualize the iterable as an array of `[key, value]` pairs (or a custom string).
689
+ * @returns Array of entries (default) or a string.
690
+ * @remarks Time O(n), Space O(n)
691
+ */
692
+ toVisual() {
693
+ return [...this];
694
+ }
695
+ /**
696
+ * Print a human-friendly representation to the console.
697
+ * @remarks Time O(n), Space O(n)
698
+ */
699
+ print() {
700
+ console.log(this.toVisual());
701
+ }
702
+ };
703
+
522
704
  // src/data-structures/queue/queue.ts
523
705
  var Queue = class _Queue extends LinearBase {
524
706
  static {
@@ -576,18 +758,52 @@ var Queue = class _Queue extends LinearBase {
576
758
  this._autoCompactRatio = value;
577
759
  }
578
760
  /**
579
- * Get the number of elements currently in the queue.
580
- * @remarks Time O(1), Space O(1)
581
- * @returns Current length.
582
- */
761
+ * Get the number of elements currently in the queue.
762
+ * @remarks Time O(1), Space O(1)
763
+ * @returns Current length.
764
+
765
+
766
+
767
+
768
+
769
+
770
+
771
+
772
+
773
+
774
+
775
+ * @example
776
+ * // Track queue length
777
+ * const q = new Queue<number>();
778
+ * console.log(q.length); // 0;
779
+ * q.push(1);
780
+ * q.push(2);
781
+ * console.log(q.length); // 2;
782
+ */
583
783
  get length() {
584
784
  return this.elements.length - this._offset;
585
785
  }
586
786
  /**
587
- * Get the first element (front) without removing it.
588
- * @remarks Time O(1), Space O(1)
589
- * @returns Front element or undefined.
590
- */
787
+ * Get the first element (front) without removing it.
788
+ * @remarks Time O(1), Space O(1)
789
+ * @returns Front element or undefined.
790
+
791
+
792
+
793
+
794
+
795
+
796
+
797
+
798
+
799
+
800
+
801
+ * @example
802
+ * // View the front element
803
+ * const q = new Queue<string>(['first', 'second', 'third']);
804
+ * console.log(q.first); // 'first';
805
+ * console.log(q.length); // 3;
806
+ */
591
807
  get first() {
592
808
  return this.length > 0 ? this.elements[this._offset] : void 0;
593
809
  }
@@ -610,19 +826,69 @@ var Queue = class _Queue extends LinearBase {
610
826
  return new _Queue(elements);
611
827
  }
612
828
  /**
613
- * Check whether the queue is empty.
614
- * @remarks Time O(1), Space O(1)
615
- * @returns True if length is 0.
616
- */
829
+ * Check whether the queue is empty.
830
+ * @remarks Time O(1), Space O(1)
831
+ * @returns True if length is 0.
832
+
833
+
834
+
835
+
836
+
837
+
838
+
839
+
840
+
841
+
842
+
843
+ * @example
844
+ * // Queue for...of iteration and isEmpty check
845
+ * const queue = new Queue<string>(['A', 'B', 'C', 'D']);
846
+ *
847
+ * const elements: string[] = [];
848
+ * for (const item of queue) {
849
+ * elements.push(item);
850
+ * }
851
+ *
852
+ * // Verify all elements are iterated in order
853
+ * console.log(elements); // ['A', 'B', 'C', 'D'];
854
+ *
855
+ * // Process all elements
856
+ * while (queue.length > 0) {
857
+ * queue.shift();
858
+ * }
859
+ *
860
+ * console.log(queue.length); // 0;
861
+ */
617
862
  isEmpty() {
618
863
  return this.length === 0;
619
864
  }
620
865
  /**
621
- * Enqueue one element at the back.
622
- * @remarks Time O(1), Space O(1)
623
- * @param element - Element to enqueue.
624
- * @returns True on success.
625
- */
866
+ * Enqueue one element at the back.
867
+ * @remarks Time O(1), Space O(1)
868
+ * @param element - Element to enqueue.
869
+ * @returns True on success.
870
+
871
+
872
+
873
+
874
+
875
+
876
+
877
+
878
+
879
+
880
+
881
+ * @example
882
+ * // basic Queue creation and push operation
883
+ * // Create a simple Queue with initial values
884
+ * const queue = new Queue([1, 2, 3, 4, 5]);
885
+ *
886
+ * // Verify the queue maintains insertion order
887
+ * console.log([...queue]); // [1, 2, 3, 4, 5];
888
+ *
889
+ * // Check length
890
+ * console.log(queue.length); // 5;
891
+ */
626
892
  push(element) {
627
893
  this.elements.push(element);
628
894
  if (this._maxLen > 0 && this.length > this._maxLen) this.shift();
@@ -643,10 +909,35 @@ var Queue = class _Queue extends LinearBase {
643
909
  return ans;
644
910
  }
645
911
  /**
646
- * Dequeue one element from the front (amortized via offset).
647
- * @remarks Time O(1) amortized, Space O(1)
648
- * @returns Removed element or undefined.
649
- */
912
+ * Dequeue one element from the front (amortized via offset).
913
+ * @remarks Time O(1) amortized, Space O(1)
914
+ * @returns Removed element or undefined.
915
+
916
+
917
+
918
+
919
+
920
+
921
+
922
+
923
+
924
+
925
+
926
+ * @example
927
+ * // Queue shift and peek operations
928
+ * const queue = new Queue<number>([10, 20, 30, 40]);
929
+ *
930
+ * // Peek at the front element without removing it
931
+ * console.log(queue.first); // 10;
932
+ *
933
+ * // Remove and get the first element (FIFO)
934
+ * const first = queue.shift();
935
+ * console.log(first); // 10;
936
+ *
937
+ * // Verify remaining elements and length decreased
938
+ * console.log([...queue]); // [20, 30, 40];
939
+ * console.log(queue.length); // 3;
940
+ */
650
941
  shift() {
651
942
  if (this.length === 0) return void 0;
652
943
  const first = this.first;
@@ -655,11 +946,24 @@ var Queue = class _Queue extends LinearBase {
655
946
  return first;
656
947
  }
657
948
  /**
658
- * Delete the first occurrence of a specific element.
659
- * @remarks Time O(N), Space O(1)
660
- * @param element - Element to remove (strict equality via Object.is).
661
- * @returns True if an element was removed.
662
- */
949
+ * Delete the first occurrence of a specific element.
950
+ * @remarks Time O(N), Space O(1)
951
+ * @param element - Element to remove (strict equality via Object.is).
952
+ * @returns True if an element was removed.
953
+
954
+
955
+
956
+
957
+
958
+
959
+
960
+
961
+ * @example
962
+ * // Remove specific element
963
+ * const q = new Queue<number>([1, 2, 3, 2]);
964
+ * q.delete(2);
965
+ * console.log(q.length); // 3;
966
+ */
663
967
  delete(element) {
664
968
  for (let i = this._offset; i < this.elements.length; i++) {
665
969
  if (Object.is(this.elements[i], element)) {
@@ -670,11 +974,24 @@ var Queue = class _Queue extends LinearBase {
670
974
  return false;
671
975
  }
672
976
  /**
673
- * Get the element at a given logical index.
674
- * @remarks Time O(1), Space O(1)
675
- * @param index - Zero-based index from the front.
676
- * @returns Element or undefined.
677
- */
977
+ * Get the element at a given logical index.
978
+ * @remarks Time O(1), Space O(1)
979
+ * @param index - Zero-based index from the front.
980
+ * @returns Element or undefined.
981
+
982
+
983
+
984
+
985
+
986
+
987
+
988
+
989
+ * @example
990
+ * // Access element by index
991
+ * const q = new Queue<string>(['a', 'b', 'c']);
992
+ * console.log(q.at(0)); // 'a';
993
+ * console.log(q.at(2)); // 'c';
994
+ */
678
995
  at(index) {
679
996
  if (index < 0 || index >= this.length) return void 0;
680
997
  return this._elements[this._offset + index];
@@ -726,19 +1043,48 @@ var Queue = class _Queue extends LinearBase {
726
1043
  return this;
727
1044
  }
728
1045
  /**
729
- * Remove all elements and reset offset.
730
- * @remarks Time O(1), Space O(1)
731
- * @returns void
732
- */
1046
+ * Remove all elements and reset offset.
1047
+ * @remarks Time O(1), Space O(1)
1048
+ * @returns void
1049
+
1050
+
1051
+
1052
+
1053
+
1054
+
1055
+
1056
+
1057
+
1058
+ * @example
1059
+ * // Remove all elements
1060
+ * const q = new Queue<number>([1, 2, 3]);
1061
+ * q.clear();
1062
+ * console.log(q.length); // 0;
1063
+ */
733
1064
  clear() {
734
1065
  this._elements = [];
735
1066
  this._offset = 0;
736
1067
  }
737
1068
  /**
738
- * Compact storage by discarding consumed head elements.
739
- * @remarks Time O(N), Space O(N)
740
- * @returns True when compaction performed.
741
- */
1069
+ * Compact storage by discarding consumed head elements.
1070
+ * @remarks Time O(N), Space O(N)
1071
+ * @returns True when compaction performed.
1072
+
1073
+
1074
+
1075
+
1076
+
1077
+
1078
+
1079
+
1080
+ * @example
1081
+ * // Reclaim unused memory
1082
+ * const q = new Queue<number>([1, 2, 3, 4, 5]);
1083
+ * q.shift();
1084
+ * q.shift();
1085
+ * q.compact();
1086
+ * console.log(q.length); // 3;
1087
+ */
742
1088
  compact() {
743
1089
  this._elements = this.elements.slice(this._offset);
744
1090
  this._offset = 0;
@@ -757,315 +1103,176 @@ var Queue = class _Queue extends LinearBase {
757
1103
  deleteCount = Math.max(0, Math.min(deleteCount, this.length - start));
758
1104
  const gi = this._offset + start;
759
1105
  const removedArray = this._elements.splice(gi, deleteCount, ...items);
760
- if (this.elements.length > 0 && this.offset / this.elements.length > this.autoCompactRatio) this.compact();
761
- const removed = this._createInstance({ toElementFn: this.toElementFn, maxLen: this._maxLen });
762
- removed._setAutoCompactRatio(this._autoCompactRatio);
763
- removed.pushMany(removedArray);
764
- return removed;
765
- }
766
- /**
767
- * Deep clone this queue and its parameters.
768
- * @remarks Time O(N), Space O(N)
769
- * @returns A new queue with the same content and options.
770
- */
771
- clone() {
772
- const out = this._createInstance({ toElementFn: this.toElementFn, maxLen: this._maxLen });
773
- out._setAutoCompactRatio(this._autoCompactRatio);
774
- for (let i = this._offset; i < this.elements.length; i++) out.push(this.elements[i]);
775
- return out;
776
- }
777
- /**
778
- * Filter elements into a new queue of the same class.
779
- * @remarks Time O(N), Space O(N)
780
- * @param predicate - Predicate (element, index, queue) → boolean to keep element.
781
- * @param [thisArg] - Value for `this` inside the predicate.
782
- * @returns A new queue with kept elements.
783
- */
784
- filter(predicate, thisArg) {
785
- const out = this._createInstance({ toElementFn: this.toElementFn, maxLen: this._maxLen });
786
- out._setAutoCompactRatio(this._autoCompactRatio);
787
- let index = 0;
788
- for (const v of this) {
789
- if (predicate.call(thisArg, v, index, this)) out.push(v);
790
- index++;
791
- }
792
- return out;
793
- }
794
- /**
795
- * Map each element to a new element in a possibly different-typed queue.
796
- * @remarks Time O(N), Space O(N)
797
- * @template EM
798
- * @template RM
799
- * @param callback - Mapping function (element, index, queue) → newElement.
800
- * @param [options] - Options for the output queue (e.g., toElementFn, maxLen, autoCompactRatio).
801
- * @param [thisArg] - Value for `this` inside the callback.
802
- * @returns A new Queue with mapped elements.
803
- */
804
- map(callback, options, thisArg) {
805
- const out = new this.constructor([], {
806
- toElementFn: options?.toElementFn,
807
- maxLen: options?.maxLen ?? this._maxLen,
808
- autoCompactRatio: options?.autoCompactRatio ?? this._autoCompactRatio
809
- });
810
- let index = 0;
811
- for (const v of this)
812
- out.push(thisArg === void 0 ? callback(v, index++, this) : callback.call(thisArg, v, index++, this));
813
- return out;
814
- }
815
- /**
816
- * Map each element to a new value of the same type.
817
- * @remarks Time O(N), Space O(N)
818
- * @param callback - Mapping function (element, index, queue) → element.
819
- * @param [thisArg] - Value for `this` inside the callback.
820
- * @returns A new queue with mapped elements (same element type).
821
- */
822
- mapSame(callback, thisArg) {
823
- const Ctor = this.constructor;
824
- const out = new Ctor([], {
825
- toElementFn: this.toElementFn,
826
- maxLen: this._maxLen,
827
- autoCompactRatio: this._autoCompactRatio
828
- });
829
- out._setAutoCompactRatio?.(this._autoCompactRatio);
830
- let index = 0;
831
- for (const v of this) {
832
- const mv = thisArg === void 0 ? callback(v, index++, this) : callback.call(thisArg, v, index++, this);
833
- out.push(mv);
834
- }
835
- return out;
836
- }
837
- /**
838
- * (Protected) Set the internal auto-compaction ratio.
839
- * @remarks Time O(1), Space O(1)
840
- * @param value - New ratio to assign.
841
- * @returns void
842
- */
843
- _setAutoCompactRatio(value) {
844
- this._autoCompactRatio = value;
845
- }
846
- /**
847
- * (Protected) Iterate elements from front to back.
848
- * @remarks Time O(N), Space O(1)
849
- * @returns Iterator of E.
850
- */
851
- *_getIterator() {
852
- for (let i = this._offset; i < this.elements.length; i++) yield this.elements[i];
853
- }
854
- /**
855
- * (Protected) Iterate elements from back to front.
856
- * @remarks Time O(N), Space O(1)
857
- * @returns Iterator of E.
858
- */
859
- *_getReverseIterator() {
860
- for (let i = this.length - 1; i >= 0; i--) {
861
- const cur = this.at(i);
862
- if (cur !== void 0) yield cur;
863
- }
864
- }
865
- /**
866
- * (Protected) Create an empty instance of the same concrete class.
867
- * @remarks Time O(1), Space O(1)
868
- * @param [options] - Options forwarded to the constructor.
869
- * @returns An empty like-kind queue instance.
870
- */
871
- _createInstance(options) {
872
- const Ctor = this.constructor;
873
- return new Ctor([], options);
874
- }
875
- /**
876
- * (Protected) Create a like-kind queue and seed it from an iterable.
877
- * @remarks Time O(N), Space O(N)
878
- * @template EM
879
- * @template RM
880
- * @param [elements] - Iterable used to seed the new queue.
881
- * @param [options] - Options forwarded to the constructor.
882
- * @returns A like-kind Queue instance.
883
- */
884
- _createLike(elements = [], options) {
885
- const Ctor = this.constructor;
886
- return new Ctor(elements, options);
887
- }
888
- };
889
-
890
- // src/data-structures/base/iterable-entry-base.ts
891
- var IterableEntryBase = class {
892
- static {
893
- __name(this, "IterableEntryBase");
894
- }
895
- /**
896
- * Default iterator yielding `[key, value]` entries.
897
- * @returns Iterator of `[K, V]`.
898
- * @remarks Time O(n) to iterate, Space O(1)
899
- */
900
- *[Symbol.iterator](...args) {
901
- yield* this._getIterator(...args);
902
- }
903
- /**
904
- * Iterate over `[key, value]` pairs (may yield `undefined` values).
905
- * @returns Iterator of `[K, V | undefined]`.
906
- * @remarks Time O(n), Space O(1)
907
- */
908
- *entries() {
909
- for (const item of this) {
910
- yield item;
911
- }
912
- }
913
- /**
914
- * Iterate over keys only.
915
- * @returns Iterator of keys.
916
- * @remarks Time O(n), Space O(1)
917
- */
918
- *keys() {
919
- for (const item of this) {
920
- yield item[0];
921
- }
922
- }
923
- /**
924
- * Iterate over values only.
925
- * @returns Iterator of values.
926
- * @remarks Time O(n), Space O(1)
927
- */
928
- *values() {
929
- for (const item of this) {
930
- yield item[1];
931
- }
932
- }
933
- /**
934
- * Test whether all entries satisfy the predicate.
935
- * @param predicate - `(key, value, index, self) => boolean`.
936
- * @param thisArg - Optional `this` for callback.
937
- * @returns `true` if all pass; otherwise `false`.
938
- * @remarks Time O(n), Space O(1)
939
- */
940
- every(predicate, thisArg) {
941
- let index = 0;
942
- for (const item of this) {
943
- if (!predicate.call(thisArg, item[1], item[0], index++, this)) {
944
- return false;
945
- }
946
- }
947
- return true;
1106
+ if (this.elements.length > 0 && this.offset / this.elements.length > this.autoCompactRatio) this.compact();
1107
+ const removed = this._createInstance({ toElementFn: this.toElementFn, maxLen: this._maxLen });
1108
+ removed._setAutoCompactRatio(this._autoCompactRatio);
1109
+ removed.pushMany(removedArray);
1110
+ return removed;
948
1111
  }
949
1112
  /**
950
- * Test whether any entry satisfies the predicate.
951
- * @param predicate - `(key, value, index, self) => boolean`.
952
- * @param thisArg - Optional `this` for callback.
953
- * @returns `true` if any passes; otherwise `false`.
954
- * @remarks Time O(n), Space O(1)
955
- */
956
- some(predicate, thisArg) {
957
- let index = 0;
958
- for (const item of this) {
959
- if (predicate.call(thisArg, item[1], item[0], index++, this)) {
960
- return true;
961
- }
962
- }
963
- return false;
1113
+ * Deep clone this queue and its parameters.
1114
+ * @remarks Time O(N), Space O(N)
1115
+ * @returns A new queue with the same content and options.
1116
+
1117
+
1118
+
1119
+
1120
+
1121
+
1122
+
1123
+
1124
+
1125
+ * @example
1126
+ * // Create independent copy
1127
+ * const q = new Queue<number>([1, 2, 3]);
1128
+ * const copy = q.clone();
1129
+ * copy.shift();
1130
+ * console.log(q.length); // 3;
1131
+ * console.log(copy.length); // 2;
1132
+ */
1133
+ clone() {
1134
+ const out = this._createInstance({ toElementFn: this.toElementFn, maxLen: this._maxLen });
1135
+ out._setAutoCompactRatio(this._autoCompactRatio);
1136
+ for (let i = this._offset; i < this.elements.length; i++) out.push(this.elements[i]);
1137
+ return out;
964
1138
  }
965
1139
  /**
966
- * Visit each entry, left-to-right.
967
- * @param callbackfn - `(key, value, index, self) => void`.
968
- * @param thisArg - Optional `this` for callback.
969
- * @remarks Time O(n), Space O(1)
970
- */
971
- forEach(callbackfn, thisArg) {
1140
+ * Filter elements into a new queue of the same class.
1141
+ * @remarks Time O(N), Space O(N)
1142
+ * @param predicate - Predicate (element, index, queue) → boolean to keep element.
1143
+ * @param [thisArg] - Value for `this` inside the predicate.
1144
+ * @returns A new queue with kept elements.
1145
+
1146
+
1147
+
1148
+
1149
+
1150
+
1151
+
1152
+
1153
+
1154
+ * @example
1155
+ * // Filter elements
1156
+ * const q = new Queue<number>([1, 2, 3, 4, 5]);
1157
+ * const evens = q.filter(x => x % 2 === 0);
1158
+ * console.log(evens.length); // 2;
1159
+ */
1160
+ filter(predicate, thisArg) {
1161
+ const out = this._createInstance({ toElementFn: this.toElementFn, maxLen: this._maxLen });
1162
+ out._setAutoCompactRatio(this._autoCompactRatio);
972
1163
  let index = 0;
973
- for (const item of this) {
974
- const [key, value] = item;
975
- callbackfn.call(thisArg, value, key, index++, this);
1164
+ for (const v of this) {
1165
+ if (predicate.call(thisArg, v, index, this)) out.push(v);
1166
+ index++;
976
1167
  }
1168
+ return out;
977
1169
  }
978
1170
  /**
979
- * Find the first entry that matches a predicate.
980
- * @param callbackfn - `(key, value, index, self) => boolean`.
981
- * @param thisArg - Optional `this` for callback.
982
- * @returns Matching `[key, value]` or `undefined`.
983
- * @remarks Time O(n), Space O(1)
984
- */
985
- find(callbackfn, thisArg) {
1171
+ * Map each element to a new element in a possibly different-typed queue.
1172
+ * @remarks Time O(N), Space O(N)
1173
+ * @template EM
1174
+ * @template RM
1175
+ * @param callback - Mapping function (element, index, queue) → newElement.
1176
+ * @param [options] - Options for the output queue (e.g., toElementFn, maxLen, autoCompactRatio).
1177
+ * @param [thisArg] - Value for `this` inside the callback.
1178
+ * @returns A new Queue with mapped elements.
1179
+
1180
+
1181
+
1182
+
1183
+
1184
+
1185
+
1186
+
1187
+ * @example
1188
+ * // Transform elements
1189
+ * const q = new Queue<number>([1, 2, 3]);
1190
+ * const doubled = q.map(x => x * 2);
1191
+ * console.log(doubled.toArray()); // [2, 4, 6];
1192
+ */
1193
+ map(callback, options, thisArg) {
1194
+ const out = new this.constructor([], {
1195
+ toElementFn: options?.toElementFn,
1196
+ maxLen: options?.maxLen ?? this._maxLen,
1197
+ autoCompactRatio: options?.autoCompactRatio ?? this._autoCompactRatio
1198
+ });
986
1199
  let index = 0;
987
- for (const item of this) {
988
- const [key, value] = item;
989
- if (callbackfn.call(thisArg, value, key, index++, this)) return item;
990
- }
991
- return;
1200
+ for (const v of this)
1201
+ out.push(thisArg === void 0 ? callback(v, index++, this) : callback.call(thisArg, v, index++, this));
1202
+ return out;
992
1203
  }
993
1204
  /**
994
- * Whether the given key exists.
995
- * @param key - Key to test.
996
- * @returns `true` if found; otherwise `false`.
997
- * @remarks Time O(n) generic, Space O(1)
1205
+ * Map each element to a new value of the same type.
1206
+ * @remarks Time O(N), Space O(N)
1207
+ * @param callback - Mapping function (element, index, queue) → element.
1208
+ * @param [thisArg] - Value for `this` inside the callback.
1209
+ * @returns A new queue with mapped elements (same element type).
998
1210
  */
999
- has(key) {
1000
- for (const item of this) {
1001
- const [itemKey] = item;
1002
- if (itemKey === key) return true;
1211
+ mapSame(callback, thisArg) {
1212
+ const Ctor = this.constructor;
1213
+ const out = new Ctor([], {
1214
+ toElementFn: this.toElementFn,
1215
+ maxLen: this._maxLen,
1216
+ autoCompactRatio: this._autoCompactRatio
1217
+ });
1218
+ out._setAutoCompactRatio?.(this._autoCompactRatio);
1219
+ let index = 0;
1220
+ for (const v of this) {
1221
+ const mv = thisArg === void 0 ? callback(v, index++, this) : callback.call(thisArg, v, index++, this);
1222
+ out.push(mv);
1003
1223
  }
1004
- return false;
1224
+ return out;
1005
1225
  }
1006
1226
  /**
1007
- * Whether there exists an entry with the given value.
1008
- * @param value - Value to test.
1009
- * @returns `true` if found; otherwise `false`.
1010
- * @remarks Time O(n), Space O(1)
1227
+ * (Protected) Set the internal auto-compaction ratio.
1228
+ * @remarks Time O(1), Space O(1)
1229
+ * @param value - New ratio to assign.
1230
+ * @returns void
1011
1231
  */
1012
- hasValue(value) {
1013
- for (const [, elementValue] of this) {
1014
- if (elementValue === value) return true;
1015
- }
1016
- return false;
1232
+ _setAutoCompactRatio(value) {
1233
+ this._autoCompactRatio = value;
1017
1234
  }
1018
1235
  /**
1019
- * Get the value under a key.
1020
- * @param key - Key to look up.
1021
- * @returns Value or `undefined`.
1022
- * @remarks Time O(n) generic, Space O(1)
1236
+ * (Protected) Iterate elements from front to back.
1237
+ * @remarks Time O(N), Space O(1)
1238
+ * @returns Iterator of E.
1023
1239
  */
1024
- get(key) {
1025
- for (const item of this) {
1026
- const [itemKey, value] = item;
1027
- if (itemKey === key) return value;
1028
- }
1029
- return;
1240
+ *_getIterator() {
1241
+ for (let i = this._offset; i < this.elements.length; i++) yield this.elements[i];
1030
1242
  }
1031
1243
  /**
1032
- * Reduce entries into a single accumulator.
1033
- * @param callbackfn - `(acc, value, key, index, self) => acc`.
1034
- * @param initialValue - Initial accumulator.
1035
- * @returns Final accumulator.
1036
- * @remarks Time O(n), Space O(1)
1244
+ * (Protected) Iterate elements from back to front.
1245
+ * @remarks Time O(N), Space O(1)
1246
+ * @returns Iterator of E.
1037
1247
  */
1038
- reduce(callbackfn, initialValue) {
1039
- let accumulator = initialValue;
1040
- let index = 0;
1041
- for (const item of this) {
1042
- const [key, value] = item;
1043
- accumulator = callbackfn(accumulator, value, key, index++, this);
1248
+ *_getReverseIterator() {
1249
+ for (let i = this.length - 1; i >= 0; i--) {
1250
+ const cur = this.at(i);
1251
+ if (cur !== void 0) yield cur;
1044
1252
  }
1045
- return accumulator;
1046
- }
1047
- /**
1048
- * Converts data structure to `[key, value]` pairs.
1049
- * @returns Array of entries.
1050
- * @remarks Time O(n), Space O(n)
1051
- */
1052
- toArray() {
1053
- return [...this];
1054
1253
  }
1055
1254
  /**
1056
- * Visualize the iterable as an array of `[key, value]` pairs (or a custom string).
1057
- * @returns Array of entries (default) or a string.
1058
- * @remarks Time O(n), Space O(n)
1255
+ * (Protected) Create an empty instance of the same concrete class.
1256
+ * @remarks Time O(1), Space O(1)
1257
+ * @param [options] - Options forwarded to the constructor.
1258
+ * @returns An empty like-kind queue instance.
1059
1259
  */
1060
- toVisual() {
1061
- return [...this];
1260
+ _createInstance(options) {
1261
+ const Ctor = this.constructor;
1262
+ return new Ctor([], options);
1062
1263
  }
1063
1264
  /**
1064
- * Print a human-friendly representation to the console.
1065
- * @remarks Time O(n), Space O(n)
1265
+ * (Protected) Create a like-kind queue and seed it from an iterable.
1266
+ * @remarks Time O(N), Space O(N)
1267
+ * @template EM
1268
+ * @template RM
1269
+ * @param [elements] - Iterable used to seed the new queue.
1270
+ * @param [options] - Options forwarded to the constructor.
1271
+ * @returns A like-kind Queue instance.
1066
1272
  */
1067
- print() {
1068
- console.log(this.toVisual());
1273
+ _createLike(elements = [], options) {
1274
+ const Ctor = this.constructor;
1275
+ return new Ctor(elements, options);
1069
1276
  }
1070
1277
  };
1071
1278
 
@@ -1442,23 +1649,71 @@ var BinaryTree = class _BinaryTree extends IterableEntryBase {
1442
1649
  return isComparable(key);
1443
1650
  }
1444
1651
  /**
1445
- * Adds a new node to the tree.
1446
- * @remarks Time O(log N), For BST, Red-Black Tree, and AVL Tree subclasses, the worst-case time is O(log N). This implementation adds the node at the first available position in a level-order (BFS) traversal. This is NOT a Binary Search Tree insertion. Time O(N), where N is the number of nodes. It must traverse level-by-level to find an empty slot. Space O(N) in the worst case for the BFS queue (e.g., a full last level).
1447
- *
1448
- * @param keyNodeOrEntry - The key, node, or entry to add.
1449
- * @returns True if the addition was successful, false otherwise.
1450
- */
1652
+ * Adds a new node to the tree.
1653
+ * @remarks Time O(log N), For BST, Red-Black Tree, and AVL Tree subclasses, the worst-case time is O(log N). This implementation adds the node at the first available position in a level-order (BFS) traversal. This is NOT a Binary Search Tree insertion. Time O(N), where N is the number of nodes. It must traverse level-by-level to find an empty slot. Space O(N) in the worst case for the BFS queue (e.g., a full last level).
1654
+ *
1655
+ * @param keyNodeOrEntry - The key, node, or entry to add.
1656
+ * @returns True if the addition was successful, false otherwise.
1657
+
1658
+
1659
+
1660
+
1661
+
1662
+
1663
+ * @example
1664
+ * // Add a single node
1665
+ * const tree = new BinaryTree<number>();
1666
+ * tree.add(1);
1667
+ * tree.add(2);
1668
+ * tree.add(3);
1669
+ * console.log(tree.size); // 3;
1670
+ * console.log(tree.has(1)); // true;
1671
+ */
1451
1672
  add(keyNodeOrEntry) {
1452
1673
  return this.set(keyNodeOrEntry);
1453
1674
  }
1454
1675
  /**
1455
- * Adds or updates a new node to the tree.
1456
- * @remarks Time O(log N), For BST, Red-Black Tree, and AVL Tree subclasses, the worst-case time is O(log N). This implementation sets the node at the first available position in a level-order (BFS) traversal. This is NOT a Binary Search Tree insertion. Time O(N), where N is the number of nodes. It must traverse level-by-level to find an empty slot. Space O(N) in the worst case for the BFS queue (e.g., a full last level).
1457
- *
1458
- * @param keyNodeOrEntry - The key, node, or entry to set or update.
1459
- * @param [value] - The value, if providing just a key.
1460
- * @returns True if the addition was successful, false otherwise.
1461
- */
1676
+ * Adds or updates a new node to the tree.
1677
+ * @remarks Time O(log N), For BST, Red-Black Tree, and AVL Tree subclasses, the worst-case time is O(log N). This implementation sets the node at the first available position in a level-order (BFS) traversal. This is NOT a Binary Search Tree insertion. Time O(N), where N is the number of nodes. It must traverse level-by-level to find an empty slot. Space O(N) in the worst case for the BFS queue (e.g., a full last level).
1678
+ *
1679
+ * @param keyNodeOrEntry - The key, node, or entry to set or update.
1680
+ * @param [value] - The value, if providing just a key.
1681
+ * @returns True if the addition was successful, false otherwise.
1682
+
1683
+
1684
+
1685
+
1686
+
1687
+
1688
+
1689
+
1690
+
1691
+
1692
+
1693
+ * @example
1694
+ * // basic BinaryTree creation and insertion
1695
+ * // Create a BinaryTree with entries
1696
+ * const entries: [number, string][] = [
1697
+ * [6, 'six'],
1698
+ * [1, 'one'],
1699
+ * [2, 'two'],
1700
+ * [7, 'seven'],
1701
+ * [5, 'five'],
1702
+ * [3, 'three'],
1703
+ * [4, 'four'],
1704
+ * [9, 'nine'],
1705
+ * [8, 'eight']
1706
+ * ];
1707
+ *
1708
+ * const tree = new BinaryTree(entries);
1709
+ *
1710
+ * // Verify size
1711
+ * console.log(tree.size); // 9;
1712
+ *
1713
+ * // Add new element
1714
+ * tree.set(10, 'ten');
1715
+ * console.log(tree.size); // 10;
1716
+ */
1462
1717
  set(keyNodeOrEntry, value) {
1463
1718
  const [newNode] = this._keyValueNodeOrEntryToNodeAndValue(keyNodeOrEntry, value);
1464
1719
  if (newNode === void 0) return false;
@@ -1503,23 +1758,44 @@ var BinaryTree = class _BinaryTree extends IterableEntryBase {
1503
1758
  return false;
1504
1759
  }
1505
1760
  /**
1506
- * Adds multiple items to the tree.
1507
- * @remarks Time O(N * M), where N is the number of items to set and M is the size of the tree at insertion (due to O(M) `set` operation). Space O(M) (from `set`) + O(N) (for the `inserted` array).
1508
- *
1509
- * @param keysNodesEntriesOrRaws - An iterable of items to set.
1510
- * @returns An array of booleans indicating the success of each individual `set` operation.
1511
- */
1761
+ * Adds multiple items to the tree.
1762
+ * @remarks Time O(N * M), where N is the number of items to set and M is the size of the tree at insertion (due to O(M) `set` operation). Space O(M) (from `set`) + O(N) (for the `inserted` array).
1763
+ *
1764
+ * @param keysNodesEntriesOrRaws - An iterable of items to set.
1765
+ * @returns An array of booleans indicating the success of each individual `set` operation.
1766
+
1767
+
1768
+
1769
+
1770
+
1771
+
1772
+
1773
+
1774
+
1775
+ * @example
1776
+ * // Bulk add
1777
+ * const tree = new BinaryTree<number>();
1778
+ * tree.addMany([1, 2, 3, 4, 5]);
1779
+ * console.log(tree.size); // 5;
1780
+ */
1512
1781
  addMany(keysNodesEntriesOrRaws) {
1513
1782
  return this.setMany(keysNodesEntriesOrRaws);
1514
1783
  }
1515
1784
  /**
1516
- * Adds or updates multiple items to the tree.
1517
- * @remarks Time O(N * M), where N is the number of items to set and M is the size of the tree at insertion (due to O(M) `set` operation). Space O(M) (from `set`) + O(N) (for the `inserted` array).
1518
- *
1519
- * @param keysNodesEntriesOrRaws - An iterable of items to set or update.
1520
- * @param [values] - An optional parallel iterable of values.
1521
- * @returns An array of booleans indicating the success of each individual `set` operation.
1522
- */
1785
+ * Adds or updates multiple items to the tree.
1786
+ * @remarks Time O(N * M), where N is the number of items to set and M is the size of the tree at insertion (due to O(M) `set` operation). Space O(M) (from `set`) + O(N) (for the `inserted` array).
1787
+ *
1788
+ * @param keysNodesEntriesOrRaws - An iterable of items to set or update.
1789
+ * @param [values] - An optional parallel iterable of values.
1790
+ * @returns An array of booleans indicating the success of each individual `set` operation.
1791
+
1792
+
1793
+ * @example
1794
+ * // Set multiple entries
1795
+ * const tree = new BinaryTree<number, string>();
1796
+ * tree.setMany([[1, 'a'], [2, 'b'], [3, 'c']]);
1797
+ * console.log(tree.size); // 3;
1798
+ */
1523
1799
  setMany(keysNodesEntriesOrRaws, values) {
1524
1800
  const inserted = [];
1525
1801
  let valuesIterator;
@@ -1540,11 +1816,26 @@ var BinaryTree = class _BinaryTree extends IterableEntryBase {
1540
1816
  return inserted;
1541
1817
  }
1542
1818
  /**
1543
- * Merges another tree into this one by seting all its nodes.
1544
- * @remarks Time O(N * M), same as `setMany`, where N is the size of `anotherTree` and M is the size of this tree. Space O(M) (from `set`).
1545
- *
1546
- * @param anotherTree - The tree to merge.
1547
- */
1819
+ * Merges another tree into this one by seting all its nodes.
1820
+ * @remarks Time O(N * M), same as `setMany`, where N is the size of `anotherTree` and M is the size of this tree. Space O(M) (from `set`).
1821
+ *
1822
+ * @param anotherTree - The tree to merge.
1823
+
1824
+
1825
+
1826
+
1827
+
1828
+
1829
+
1830
+
1831
+
1832
+ * @example
1833
+ * // Combine trees
1834
+ * const t1 = new BinaryTree<number>([1, 2]);
1835
+ * const t2 = new BinaryTree<number>([3, 4]);
1836
+ * t1.merge(t2);
1837
+ * console.log(t1.size); // 4;
1838
+ */
1548
1839
  merge(anotherTree) {
1549
1840
  this.setMany(anotherTree, []);
1550
1841
  }
@@ -1560,12 +1851,29 @@ var BinaryTree = class _BinaryTree extends IterableEntryBase {
1560
1851
  this.setMany(keysNodesEntriesOrRaws, values);
1561
1852
  }
1562
1853
  /**
1563
- * Deletes a node from the tree.
1564
- * @remarks Time O(log N), For BST, Red-Black Tree, and AVL Tree subclasses, the worst-case time is O(log N). This implementation finds the node, and if it has two children, swaps it with the rightmost node of its left subtree (in-order predecessor) before deleting. Time O(N) in the worst case. O(N) to find the node (`getNode`) and O(H) (which is O(N) worst-case) to find the rightmost node. Space O(1) (if `getNode` is iterative, which it is).
1565
- *
1566
- * @param keyNodeEntryRawOrPredicate - The node to delete.
1567
- * @returns An array containing deletion results (for compatibility with self-balancing trees).
1568
- */
1854
+ * Deletes a node from the tree.
1855
+ * @remarks Time O(log N), For BST, Red-Black Tree, and AVL Tree subclasses, the worst-case time is O(log N). This implementation finds the node, and if it has two children, swaps it with the rightmost node of its left subtree (in-order predecessor) before deleting. Time O(N) in the worst case. O(N) to find the node (`getNode`) and O(H) (which is O(N) worst-case) to find the rightmost node. Space O(1) (if `getNode` is iterative, which it is).
1856
+ *
1857
+ * @param keyNodeEntryRawOrPredicate - The node to delete.
1858
+ * @returns An array containing deletion results (for compatibility with self-balancing trees).
1859
+
1860
+
1861
+
1862
+
1863
+
1864
+
1865
+
1866
+
1867
+
1868
+
1869
+
1870
+ * @example
1871
+ * // Remove a node
1872
+ * const tree = new BinaryTree<number>([1, 2, 3, 4, 5]);
1873
+ * tree.delete(3);
1874
+ * console.log(tree.has(3)); // false;
1875
+ * console.log(tree.size); // 4;
1876
+ */
1569
1877
  delete(keyNodeEntryRawOrPredicate) {
1570
1878
  const deletedResult = [];
1571
1879
  if (!this._root) return deletedResult;
@@ -1659,14 +1967,27 @@ var BinaryTree = class _BinaryTree extends IterableEntryBase {
1659
1967
  return this.search(keyNodeEntryOrPredicate, onlyOne, (node) => node, startNode, iterationType);
1660
1968
  }
1661
1969
  /**
1662
- * Gets the first node matching a predicate.
1663
- * @remarks Time O(log N), For BST, Red-Black Tree, and AVL Tree subclasses, the worst-case time is O(log N). Time O(N) in the worst case (via `search`). Space O(H) or O(N) (via `search`).
1664
- *
1665
- * @param keyNodeEntryOrPredicate - The key, node, entry, or predicate function to search for.
1666
- * @param [startNode=this._root] - The node to start the search from.
1667
- * @param [iterationType=this.iterationType] - The traversal method.
1668
- * @returns The first matching node, or undefined if not found.
1669
- */
1970
+ * Gets the first node matching a predicate.
1971
+ * @remarks Time O(log N), For BST, Red-Black Tree, and AVL Tree subclasses, the worst-case time is O(log N). Time O(N) in the worst case (via `search`). Space O(H) or O(N) (via `search`).
1972
+ *
1973
+ * @param keyNodeEntryOrPredicate - The key, node, entry, or predicate function to search for.
1974
+ * @param [startNode=this._root] - The node to start the search from.
1975
+ * @param [iterationType=this.iterationType] - The traversal method.
1976
+ * @returns The first matching node, or undefined if not found.
1977
+
1978
+
1979
+
1980
+
1981
+
1982
+
1983
+
1984
+
1985
+
1986
+ * @example
1987
+ * // Get node by key
1988
+ * const tree = new BinaryTree<number, string>([[1, 'root'], [2, 'child']]);
1989
+ * console.log(tree.getNode(2)?.value); // 'child';
1990
+ */
1670
1991
  getNode(keyNodeEntryOrPredicate, startNode = this._root, iterationType = this.iterationType) {
1671
1992
  if (this._isMapMode && keyNodeEntryOrPredicate !== null && keyNodeEntryOrPredicate !== void 0) {
1672
1993
  if (!this._isPredicate(keyNodeEntryOrPredicate)) {
@@ -1678,14 +1999,30 @@ var BinaryTree = class _BinaryTree extends IterableEntryBase {
1678
1999
  return this.search(keyNodeEntryOrPredicate, true, (node) => node, startNode, iterationType)[0];
1679
2000
  }
1680
2001
  /**
1681
- * Gets the value associated with a key.
1682
- * @remarks Time O(log N), For BST, Red-Black Tree, and AVL Tree subclasses, the worst-case time is O(log N). Time O(1) if in Map mode. O(N) if not in Map mode (uses `getNode`). Space O(1) if in Map mode. O(H) or O(N) otherwise.
1683
- *
1684
- * @param keyNodeEntryOrPredicate - The key, node, or entry to get the value for.
1685
- * @param [startNode=this._root] - The node to start searching from (if not in Map mode).
1686
- * @param [iterationType=this.iterationType] - The traversal method (if not in Map mode).
1687
- * @returns The associated value, or undefined.
1688
- */
2002
+ * Gets the value associated with a key.
2003
+ * @remarks Time O(log N), For BST, Red-Black Tree, and AVL Tree subclasses, the worst-case time is O(log N). Time O(1) if in Map mode. O(N) if not in Map mode (uses `getNode`). Space O(1) if in Map mode. O(H) or O(N) otherwise.
2004
+ *
2005
+ * @param keyNodeEntryOrPredicate - The key, node, or entry to get the value for.
2006
+ * @param [startNode=this._root] - The node to start searching from (if not in Map mode).
2007
+ * @param [iterationType=this.iterationType] - The traversal method (if not in Map mode).
2008
+ * @returns The associated value, or undefined.
2009
+
2010
+
2011
+
2012
+
2013
+
2014
+
2015
+
2016
+
2017
+
2018
+
2019
+
2020
+ * @example
2021
+ * // Retrieve value by key
2022
+ * const tree = new BinaryTree<number, string>([[1, 'root'], [2, 'left'], [3, 'right']]);
2023
+ * console.log(tree.get(2)); // 'left';
2024
+ * console.log(tree.get(99)); // undefined;
2025
+ */
1689
2026
  get(keyNodeEntryOrPredicate, startNode = this._root, iterationType = this.iterationType) {
1690
2027
  if (this._isMapMode) {
1691
2028
  const key = this._extractKey(keyNodeEntryOrPredicate);
@@ -1705,19 +2042,45 @@ var BinaryTree = class _BinaryTree extends IterableEntryBase {
1705
2042
  return this.search(keyNodeEntryOrPredicate, true, (node) => node, startNode, iterationType).length > 0;
1706
2043
  }
1707
2044
  /**
1708
- * Clears the tree of all nodes and values.
1709
- * @remarks Time O(N) if in Map mode (due to `_store.clear()`), O(1) otherwise. Space O(1)
1710
- */
2045
+ * Clears the tree of all nodes and values.
2046
+ * @remarks Time O(N) if in Map mode (due to `_store.clear()`), O(1) otherwise. Space O(1)
2047
+
2048
+
2049
+
2050
+
2051
+
2052
+
2053
+
2054
+
2055
+
2056
+ * @example
2057
+ * // Remove all nodes
2058
+ * const tree = new BinaryTree<number>([1, 2, 3]);
2059
+ * tree.clear();
2060
+ * console.log(tree.isEmpty()); // true;
2061
+ */
1711
2062
  clear() {
1712
2063
  this._clearNodes();
1713
2064
  if (this._isMapMode) this._clearValues();
1714
2065
  }
1715
2066
  /**
1716
- * Checks if the tree is empty.
1717
- * @remarks Time O(1), Space O(1)
1718
- *
1719
- * @returns True if the tree has no nodes, false otherwise.
1720
- */
2067
+ * Checks if the tree is empty.
2068
+ * @remarks Time O(1), Space O(1)
2069
+ *
2070
+ * @returns True if the tree has no nodes, false otherwise.
2071
+
2072
+
2073
+
2074
+
2075
+
2076
+
2077
+
2078
+
2079
+
2080
+ * @example
2081
+ * // Check empty
2082
+ * console.log(new BinaryTree().isEmpty()); // true;
2083
+ */
1721
2084
  isEmpty() {
1722
2085
  return this._size === 0;
1723
2086
  }
@@ -1732,13 +2095,27 @@ var BinaryTree = class _BinaryTree extends IterableEntryBase {
1732
2095
  return this.getMinHeight(startNode) + 1 >= this.getHeight(startNode);
1733
2096
  }
1734
2097
  /**
1735
- * Checks if the tree is a valid Binary Search Tree (BST).
1736
- * @remarks Time O(N), as it must visit every node. Space O(H) for the call stack (recursive) or explicit stack (iterative), where H is the tree height (O(N) worst-case).
1737
- *
1738
- * @param [startNode=this._root] - The node to start checking from.
1739
- * @param [iterationType=this.iterationType] - The traversal method.
1740
- * @returns True if it's a valid BST, false otherwise.
1741
- */
2098
+ * Checks if the tree is a valid Binary Search Tree (BST).
2099
+ * @remarks Time O(N), as it must visit every node. Space O(H) for the call stack (recursive) or explicit stack (iterative), where H is the tree height (O(N) worst-case).
2100
+ *
2101
+ * @param [startNode=this._root] - The node to start checking from.
2102
+ * @param [iterationType=this.iterationType] - The traversal method.
2103
+ * @returns True if it's a valid BST, false otherwise.
2104
+
2105
+
2106
+
2107
+
2108
+
2109
+
2110
+
2111
+
2112
+
2113
+ * @example
2114
+ * // Check BST property
2115
+ * const tree = new BinaryTree<number>([1, 2, 3]);
2116
+ * // BinaryTree doesn't guarantee BST order
2117
+ * console.log(typeof tree.isBST()); // 'boolean';
2118
+ */
1742
2119
  isBST(startNode = this._root, iterationType = this.iterationType) {
1743
2120
  const startNodeSired = this.ensureNode(startNode);
1744
2121
  if (!startNodeSired) return true;
@@ -1776,13 +2153,29 @@ var BinaryTree = class _BinaryTree extends IterableEntryBase {
1776
2153
  }
1777
2154
  }
1778
2155
  /**
1779
- * Gets the depth of a node (distance from `startNode`).
1780
- * @remarks Time O(H), where H is the depth of the `dist` node relative to `startNode`. O(N) worst-case. Space O(1).
1781
- *
1782
- * @param dist - The node to find the depth of.
1783
- * @param [startNode=this._root] - The node to measure depth from (defaults to root).
1784
- * @returns The depth (0 if `dist` is `startNode`).
1785
- */
2156
+ * Gets the depth of a node (distance from `startNode`).
2157
+ * @remarks Time O(H), where H is the depth of the `dist` node relative to `startNode`. O(N) worst-case. Space O(1).
2158
+ *
2159
+ * @param dist - The node to find the depth of.
2160
+ * @param [startNode=this._root] - The node to measure depth from (defaults to root).
2161
+ * @returns The depth (0 if `dist` is `startNode`).
2162
+
2163
+
2164
+
2165
+
2166
+
2167
+
2168
+
2169
+
2170
+
2171
+
2172
+
2173
+ * @example
2174
+ * // Get depth of a node
2175
+ * const tree = new BinaryTree<number>([1, 2, 3, 4, 5]);
2176
+ * const node = tree.getNode(4);
2177
+ * console.log(tree.getDepth(node!)); // 2;
2178
+ */
1786
2179
  getDepth(dist, startNode = this._root) {
1787
2180
  let distEnsured = this.ensureNode(dist);
1788
2181
  const beginRootEnsured = this.ensureNode(startNode);
@@ -1797,13 +2190,28 @@ var BinaryTree = class _BinaryTree extends IterableEntryBase {
1797
2190
  return depth;
1798
2191
  }
1799
2192
  /**
1800
- * Gets the maximum height of the tree (longest path from startNode to a leaf).
1801
- * @remarks Time O(N), as it must visit every node. Space O(H) for recursive stack (O(N) worst-case) or O(N) for iterative stack (storing node + depth).
1802
- *
1803
- * @param [startNode=this._root] - The node to start measuring from.
1804
- * @param [iterationType=this.iterationType] - The traversal method.
1805
- * @returns The height ( -1 for an empty tree, 0 for a single-node tree).
1806
- */
2193
+ * Gets the maximum height of the tree (longest path from startNode to a leaf).
2194
+ * @remarks Time O(N), as it must visit every node. Space O(H) for recursive stack (O(N) worst-case) or O(N) for iterative stack (storing node + depth).
2195
+ *
2196
+ * @param [startNode=this._root] - The node to start measuring from.
2197
+ * @param [iterationType=this.iterationType] - The traversal method.
2198
+ * @returns The height ( -1 for an empty tree, 0 for a single-node tree).
2199
+
2200
+
2201
+
2202
+
2203
+
2204
+
2205
+
2206
+
2207
+
2208
+
2209
+
2210
+ * @example
2211
+ * // Get tree height
2212
+ * const tree = new BinaryTree<number>([1, 2, 3, 4, 5]);
2213
+ * console.log(tree.getHeight()); // 2;
2214
+ */
1807
2215
  getHeight(startNode = this._root, iterationType = this.iterationType) {
1808
2216
  startNode = this.ensureNode(startNode);
1809
2217
  if (!this.isRealNode(startNode)) return -1;
@@ -2239,24 +2647,53 @@ var BinaryTree = class _BinaryTree extends IterableEntryBase {
2239
2647
  return ans;
2240
2648
  }
2241
2649
  /**
2242
- * Clones the tree.
2243
- * @remarks Time O(N * M), where N is the number of nodes and M is the tree size during insertion (due to `bfs` + `set`, and `set` is O(M)). Space O(N) for the new tree and the BFS queue.
2244
- *
2245
- * @returns A new, cloned instance of the tree.
2246
- */
2650
+ * Clones the tree.
2651
+ * @remarks Time O(N * M), where N is the number of nodes and M is the tree size during insertion (due to `bfs` + `set`, and `set` is O(M)). Space O(N) for the new tree and the BFS queue.
2652
+ *
2653
+ * @returns A new, cloned instance of the tree.
2654
+
2655
+
2656
+
2657
+
2658
+
2659
+
2660
+
2661
+
2662
+
2663
+ * @example
2664
+ * // Deep copy
2665
+ * const tree = new BinaryTree<number>([1, 2, 3]);
2666
+ * const copy = tree.clone();
2667
+ * copy.delete(1);
2668
+ * console.log(tree.has(1)); // true;
2669
+ */
2247
2670
  clone() {
2248
2671
  const out = this._createInstance();
2249
2672
  this._clone(out);
2250
2673
  return out;
2251
2674
  }
2252
2675
  /**
2253
- * Creates a new tree containing only the entries that satisfy the predicate.
2254
- * @remarks Time O(N * M), where N is nodes in this tree, and M is size of the new tree during insertion (O(N) iteration + O(M) `set` for each item). Space O(N) for the new tree.
2255
- *
2256
- * @param predicate - A function to test each [key, value] pair.
2257
- * @param [thisArg] - `this` context for the predicate.
2258
- * @returns A new, filtered tree.
2259
- */
2676
+ * Creates a new tree containing only the entries that satisfy the predicate.
2677
+ * @remarks Time O(N * M), where N is nodes in this tree, and M is size of the new tree during insertion (O(N) iteration + O(M) `set` for each item). Space O(N) for the new tree.
2678
+ *
2679
+ * @param predicate - A function to test each [key, value] pair.
2680
+ * @param [thisArg] - `this` context for the predicate.
2681
+ * @returns A new, filtered tree.
2682
+
2683
+
2684
+
2685
+
2686
+
2687
+
2688
+
2689
+
2690
+
2691
+ * @example
2692
+ * // Filter nodes by condition
2693
+ * const tree = new BinaryTree<number>([1, 2, 3, 4]);
2694
+ * const result = tree.filter((_, key) => key > 2);
2695
+ * console.log(result.size); // 2;
2696
+ */
2260
2697
  filter(predicate, thisArg) {
2261
2698
  const out = this._createInstance();
2262
2699
  let i = 0;
@@ -2264,17 +2701,31 @@ var BinaryTree = class _BinaryTree extends IterableEntryBase {
2264
2701
  return out;
2265
2702
  }
2266
2703
  /**
2267
- * Creates a new tree by mapping each [key, value] pair to a new entry.
2268
- * @remarks Time O(N * M), where N is nodes in this tree, and M is size of the new tree during insertion. Space O(N) for the new tree.
2269
- *
2270
- * @template MK - New key type.
2271
- * @template MV - New value type.
2272
- * @template MR - New raw type.
2273
- * @param cb - A function to map each [key, value] pair.
2274
- * @param [options] - Options for the new tree.
2275
- * @param [thisArg] - `this` context for the callback.
2276
- * @returns A new, mapped tree.
2277
- */
2704
+ * Creates a new tree by mapping each [key, value] pair to a new entry.
2705
+ * @remarks Time O(N * M), where N is nodes in this tree, and M is size of the new tree during insertion. Space O(N) for the new tree.
2706
+ *
2707
+ * @template MK - New key type.
2708
+ * @template MV - New value type.
2709
+ * @template MR - New raw type.
2710
+ * @param cb - A function to map each [key, value] pair.
2711
+ * @param [options] - Options for the new tree.
2712
+ * @param [thisArg] - `this` context for the callback.
2713
+ * @returns A new, mapped tree.
2714
+
2715
+
2716
+
2717
+
2718
+
2719
+
2720
+
2721
+
2722
+
2723
+ * @example
2724
+ * // Transform to new tree
2725
+ * const tree = new BinaryTree<number, number>([[1, 10], [2, 20]]);
2726
+ * const mapped = tree.map((v, key) => [key, (v ?? 0) + 1] as [number, number]);
2727
+ * console.log([...mapped.values()]); // contains 11;
2728
+ */
2278
2729
  map(cb, options, thisArg) {
2279
2730
  const out = this._createLike([], options);
2280
2731
  let i = 0;
@@ -2312,12 +2763,25 @@ var BinaryTree = class _BinaryTree extends IterableEntryBase {
2312
2763
  return output;
2313
2764
  }
2314
2765
  /**
2315
- * Prints a visual representation of the tree to the console.
2316
- * @remarks Time O(N) (via `toVisual`). Space O(N*H) or O(N^2) (via `toVisual`).
2317
- *
2318
- * @param [options] - Options to control the output.
2319
- * @param [startNode=this._root] - The node to start printing from.
2320
- */
2766
+ * Prints a visual representation of the tree to the console.
2767
+ * @remarks Time O(N) (via `toVisual`). Space O(N*H) or O(N^2) (via `toVisual`).
2768
+ *
2769
+ * @param [options] - Options to control the output.
2770
+ * @param [startNode=this._root] - The node to start printing from.
2771
+
2772
+
2773
+
2774
+
2775
+
2776
+
2777
+
2778
+
2779
+
2780
+ * @example
2781
+ * // Display tree
2782
+ * const tree = new BinaryTree<number>([1, 2, 3]);
2783
+ * expect(() => tree.print()).not.toThrow();
2784
+ */
2321
2785
  print(options, startNode = this._root) {
2322
2786
  console.log(this.toVisual(startNode, options));
2323
2787
  }
@@ -2556,7 +3020,6 @@ var BinaryTree = class _BinaryTree extends IterableEntryBase {
2556
3020
  * @returns Layout information for this subtree.
2557
3021
  */
2558
3022
  _displayAux(node, options) {
2559
- const { isShowNull, isShowUndefined, isShowRedBlackNIL } = options;
2560
3023
  const emptyDisplayLayout = [["\u2500"], 1, 0, 0];
2561
3024
  const newFrame = /* @__PURE__ */ __name((n) => ({
2562
3025
  node: n,
@@ -2852,6 +3315,7 @@ var BSTNode = class {
2852
3315
  *
2853
3316
  * @returns The height.
2854
3317
  */
3318
+ /* istanbul ignore next -- covered by AVLTree/RedBlackTree tests (subclass uses height) */
2855
3319
  get height() {
2856
3320
  return this._height;
2857
3321
  }
@@ -2861,6 +3325,7 @@ var BSTNode = class {
2861
3325
  *
2862
3326
  * @param value - The new height.
2863
3327
  */
3328
+ /* istanbul ignore next -- covered by AVLTree/RedBlackTree tests (subclass uses height) */
2864
3329
  set height(value) {
2865
3330
  this._height = value;
2866
3331
  }
@@ -2871,6 +3336,7 @@ var BSTNode = class {
2871
3336
  *
2872
3337
  * @returns The node's color.
2873
3338
  */
3339
+ /* istanbul ignore next -- covered by RedBlackTree tests (subclass uses color) */
2874
3340
  get color() {
2875
3341
  return this._color;
2876
3342
  }
@@ -2880,6 +3346,7 @@ var BSTNode = class {
2880
3346
  *
2881
3347
  * @param value - The new color.
2882
3348
  */
3349
+ /* istanbul ignore next -- covered by RedBlackTree tests (subclass uses color) */
2883
3350
  set color(value) {
2884
3351
  this._color = value;
2885
3352
  }
@@ -2890,6 +3357,7 @@ var BSTNode = class {
2890
3357
  *
2891
3358
  * @returns The subtree node count.
2892
3359
  */
3360
+ /* istanbul ignore next -- internal field used by subclasses */
2893
3361
  get count() {
2894
3362
  return this._count;
2895
3363
  }
@@ -2899,6 +3367,7 @@ var BSTNode = class {
2899
3367
  *
2900
3368
  * @param value - The new count.
2901
3369
  */
3370
+ /* istanbul ignore next -- internal field used by subclasses */
2902
3371
  set count(value) {
2903
3372
  this._count = value;
2904
3373
  }
@@ -3053,14 +3522,39 @@ var BST = class extends BinaryTree {
3053
3522
  return super.listLevels(callback, startNode, iterationType, false);
3054
3523
  }
3055
3524
  /**
3056
- * Gets the first node matching a predicate.
3057
- * @remarks Time O(log N) if searching by key, O(N) if searching by predicate. Space O(log N) or O(N).
3058
- *
3059
- * @param keyNodeEntryOrPredicate - The key, node, entry, or predicate function to search for.
3060
- * @param [startNode=this._root] - The node to start the search from.
3061
- * @param [iterationType=this.iterationType] - The traversal method.
3062
- * @returns The first matching node, or undefined if not found.
3063
- */
3525
+ * Gets the first node matching a predicate.
3526
+ * @remarks Time O(log N) if searching by key, O(N) if searching by predicate. Space O(log N) or O(N).
3527
+ *
3528
+ * @param keyNodeEntryOrPredicate - The key, node, entry, or predicate function to search for.
3529
+ * @param [startNode=this._root] - The node to start the search from.
3530
+ * @param [iterationType=this.iterationType] - The traversal method.
3531
+ * @returns The first matching node, or undefined if not found.
3532
+
3533
+
3534
+
3535
+
3536
+
3537
+
3538
+
3539
+
3540
+
3541
+
3542
+
3543
+
3544
+
3545
+
3546
+
3547
+
3548
+
3549
+
3550
+
3551
+ * @example
3552
+ * // Get node object by key
3553
+ * const bst = new BST<number, string>([[5, 'root'], [3, 'left'], [7, 'right']]);
3554
+ * const node = bst.getNode(3);
3555
+ * console.log(node?.key); // 3;
3556
+ * console.log(node?.value); // 'left';
3557
+ */
3064
3558
  getNode(keyNodeEntryOrPredicate, startNode = this._root, iterationType = this.iterationType) {
3065
3559
  if (keyNodeEntryOrPredicate === null || keyNodeEntryOrPredicate === void 0) return void 0;
3066
3560
  if (this._isPredicate(keyNodeEntryOrPredicate)) {
@@ -3209,13 +3703,44 @@ var BST = class extends BinaryTree {
3209
3703
  return this.search(searchRange, false, callback, startNode, iterationType);
3210
3704
  }
3211
3705
  /**
3212
- * Adds a new node to the BST based on key comparison.
3213
- * @remarks Time O(log N), where H is tree height. O(N) worst-case (unbalanced tree), O(log N) average. Space O(1).
3214
- *
3215
- * @param keyNodeOrEntry - The key, node, or entry to set.
3216
- * @param [value] - The value, if providing just a key.
3217
- * @returns True if the addition was successful, false otherwise.
3218
- */
3706
+ * Adds a new node to the BST based on key comparison.
3707
+ * @remarks Time O(log N), where H is tree height. O(N) worst-case (unbalanced tree), O(log N) average. Space O(1).
3708
+ *
3709
+ * @param keyNodeOrEntry - The key, node, or entry to set.
3710
+ * @param [value] - The value, if providing just a key.
3711
+ * @returns True if the addition was successful, false otherwise.
3712
+
3713
+
3714
+
3715
+
3716
+
3717
+
3718
+
3719
+
3720
+
3721
+
3722
+
3723
+
3724
+
3725
+
3726
+
3727
+
3728
+
3729
+
3730
+
3731
+
3732
+
3733
+
3734
+
3735
+
3736
+
3737
+ * @example
3738
+ * // Set a key-value pair
3739
+ * const bst = new BST<number, string>();
3740
+ * bst.set(1, 'one');
3741
+ * bst.set(2, 'two');
3742
+ * console.log(bst.get(1)); // 'one';
3743
+ */
3219
3744
  set(keyNodeOrEntry, value) {
3220
3745
  const [newNode] = this._keyValueNodeOrEntryToNodeAndValue(keyNodeOrEntry, value);
3221
3746
  if (newNode === void 0) return false;
@@ -3252,17 +3777,34 @@ var BST = class extends BinaryTree {
3252
3777
  return false;
3253
3778
  }
3254
3779
  /**
3255
- * Adds multiple items to the tree.
3256
- * @remarks If `isBalanceAdd` is true, sorts the input and builds a balanced tree. Time O(N log N) (due to sort and balanced set).
3257
- * If false, adds items one by one. Time O(N * H), which is O(N^2) worst-case.
3258
- * Space O(N) for sorting and recursion/iteration stack.
3259
- *
3260
- * @param keysNodesEntriesOrRaws - An iterable of items to set.
3261
- * @param [values] - An optional parallel iterable of values.
3262
- * @param [isBalanceAdd=true] - If true, builds a balanced tree from the items.
3263
- * @param [iterationType=this.iterationType] - The traversal method for balanced set (recursive or iterative).
3264
- * @returns An array of booleans indicating the success of each individual `set` operation.
3265
- */
3780
+ * Adds multiple items to the tree.
3781
+ * @remarks If `isBalanceAdd` is true, sorts the input and builds a balanced tree. Time O(N log N) (due to sort and balanced set).
3782
+ * If false, adds items one by one. Time O(N * H), which is O(N^2) worst-case.
3783
+ * Space O(N) for sorting and recursion/iteration stack.
3784
+ *
3785
+ * @param keysNodesEntriesOrRaws - An iterable of items to set.
3786
+ * @param [values] - An optional parallel iterable of values.
3787
+ * @param [isBalanceAdd=true] - If true, builds a balanced tree from the items.
3788
+ * @param [iterationType=this.iterationType] - The traversal method for balanced set (recursive or iterative).
3789
+ * @returns An array of booleans indicating the success of each individual `set` operation.
3790
+
3791
+
3792
+
3793
+
3794
+
3795
+
3796
+
3797
+
3798
+
3799
+
3800
+
3801
+ * @example
3802
+ * // Set multiple key-value pairs
3803
+ * const bst = new BST<number, string>();
3804
+ * bst.setMany([[1, 'a'], [2, 'b'], [3, 'c']]);
3805
+ * console.log(bst.size); // 3;
3806
+ * console.log(bst.get(2)); // 'b';
3807
+ */
3266
3808
  setMany(keysNodesEntriesOrRaws, values, isBalanceAdd = true, iterationType = this.iterationType) {
3267
3809
  const inserted = [];
3268
3810
  const valuesIterator = values?.[Symbol.iterator]();
@@ -3505,12 +4047,29 @@ var BST = class extends BinaryTree {
3505
4047
  }
3506
4048
  }
3507
4049
  /**
3508
- * Rebuilds the tree to be perfectly balanced.
3509
- * @remarks Time O(N) (O(N) for DFS, O(N) for sorted build). Space O(N) for node array and recursion stack.
3510
- *
3511
- * @param [iterationType=this.iterationType] - The traversal method for the initial node export.
3512
- * @returns True if successful, false if the tree was empty.
3513
- */
4050
+ * Rebuilds the tree to be perfectly balanced.
4051
+ * @remarks Time O(N) (O(N) for DFS, O(N) for sorted build). Space O(N) for node array and recursion stack.
4052
+ *
4053
+ * @param [iterationType=this.iterationType] - The traversal method for the initial node export.
4054
+ * @returns True if successful, false if the tree was empty.
4055
+
4056
+
4057
+
4058
+
4059
+
4060
+
4061
+
4062
+
4063
+
4064
+ * @example
4065
+ * // Rebalance the tree
4066
+ * const bst = new BST<number>();
4067
+ * // Insert in sorted order (worst case for BST)
4068
+ * for (let i = 1; i <= 7; i++) bst.add(i);
4069
+ * console.log(bst.isAVLBalanced()); // false;
4070
+ * bst.perfectlyBalance();
4071
+ * console.log(bst.isAVLBalanced()); // true;
4072
+ */
3514
4073
  perfectlyBalance(iterationType = this.iterationType) {
3515
4074
  const nodes = this.dfs((node) => node, "IN", false, this._root, iterationType);
3516
4075
  const n = nodes.length;
@@ -3533,12 +4092,25 @@ var BST = class extends BinaryTree {
3533
4092
  return true;
3534
4093
  }
3535
4094
  /**
3536
- * Checks if the tree meets the AVL balance condition (height difference <= 1).
3537
- * @remarks Time O(N), as it must visit every node to compute height. Space O(log N) for recursion or O(N) for iterative map.
3538
- *
3539
- * @param [iterationType=this.iterationType] - The traversal method.
3540
- * @returns True if the tree is AVL balanced, false otherwise.
3541
- */
4095
+ * Checks if the tree meets the AVL balance condition (height difference <= 1).
4096
+ * @remarks Time O(N), as it must visit every node to compute height. Space O(log N) for recursion or O(N) for iterative map.
4097
+ *
4098
+ * @param [iterationType=this.iterationType] - The traversal method.
4099
+ * @returns True if the tree is AVL balanced, false otherwise.
4100
+
4101
+
4102
+
4103
+
4104
+
4105
+
4106
+
4107
+
4108
+
4109
+ * @example
4110
+ * // Check if tree is height-balanced
4111
+ * const bst = new BST<number>([3, 1, 5, 2, 4]);
4112
+ * console.log(bst.isAVLBalanced()); // true;
4113
+ */
3542
4114
  isAVLBalanced(iterationType = this.iterationType) {
3543
4115
  if (!this._root) return true;
3544
4116
  let balanced = true;
@@ -3578,18 +4150,42 @@ var BST = class extends BinaryTree {
3578
4150
  return balanced;
3579
4151
  }
3580
4152
  /**
3581
- * Creates a new BST by mapping each [key, value] pair to a new entry.
3582
- * @remarks Time O(N * H), where N is nodes in this tree, and H is height of the new tree during insertion.
3583
- * Space O(N) for the new tree.
3584
- *
3585
- * @template MK - New key type.
3586
- * @template MV - New value type.
3587
- * @template MR - New raw type.
3588
- * @param callback - A function to map each [key, value] pair.
3589
- * @param [options] - Options for the new BST.
3590
- * @param [thisArg] - `this` context for the callback.
3591
- * @returns A new, mapped BST.
3592
- */
4153
+ * Creates a new BST by mapping each [key, value] pair to a new entry.
4154
+ * @remarks Time O(N * H), where N is nodes in this tree, and H is height of the new tree during insertion.
4155
+ * Space O(N) for the new tree.
4156
+ *
4157
+ * @template MK - New key type.
4158
+ * @template MV - New value type.
4159
+ * @template MR - New raw type.
4160
+ * @param callback - A function to map each [key, value] pair.
4161
+ * @param [options] - Options for the new BST.
4162
+ * @param [thisArg] - `this` context for the callback.
4163
+ * @returns A new, mapped BST.
4164
+
4165
+
4166
+
4167
+
4168
+
4169
+
4170
+
4171
+
4172
+
4173
+
4174
+
4175
+
4176
+
4177
+
4178
+
4179
+
4180
+
4181
+
4182
+
4183
+ * @example
4184
+ * // Transform to new tree
4185
+ * const bst = new BST<number, number>([[1, 10], [2, 20], [3, 30]]);
4186
+ * const doubled = bst.map((value, key) => [key, (value ?? 0) * 2] as [number, number]);
4187
+ * console.log([...doubled.values()]); // [20, 40, 60];
4188
+ */
3593
4189
  map(callback, options, thisArg) {
3594
4190
  const out = this._createLike([], options);
3595
4191
  let index = 0;
@@ -4160,15 +4756,12 @@ var AVLTreeNode = class {
4160
4756
  *
4161
4757
  * @returns The node's color.
4162
4758
  */
4759
+ /* istanbul ignore next -- inherited field, used by RedBlackTree subclass */
4760
+ /* istanbul ignore next -- inherited field, not used by AVLTree */
4163
4761
  get color() {
4164
4762
  return this._color;
4165
4763
  }
4166
- /**
4167
- * Sets the color of the node.
4168
- * @remarks Time O(1), Space O(1)
4169
- *
4170
- * @param value - The new color.
4171
- */
4764
+ /* istanbul ignore next -- inherited field, not used by AVLTree */
4172
4765
  set color(value) {
4173
4766
  this._color = value;
4174
4767
  }
@@ -4179,15 +4772,11 @@ var AVLTreeNode = class {
4179
4772
  *
4180
4773
  * @returns The subtree node count.
4181
4774
  */
4775
+ /* istanbul ignore next -- inherited field, not used by AVLTree */
4182
4776
  get count() {
4183
4777
  return this._count;
4184
4778
  }
4185
- /**
4186
- * Sets the count of nodes in the subtree.
4187
- * @remarks Time O(1), Space O(1)
4188
- *
4189
- * @param value - The new count.
4190
- */
4779
+ /* istanbul ignore next -- inherited field, not used by AVLTree */
4191
4780
  set count(value) {
4192
4781
  this._count = value;
4193
4782
  }
@@ -4246,13 +4835,55 @@ var AVLTree = class extends BST {
4246
4835
  return keyNodeOrEntry instanceof AVLTreeNode;
4247
4836
  }
4248
4837
  /**
4249
- * Sets a new node to the AVL tree and balances the tree path.
4250
- * @remarks Time O(log N) (O(H) for BST set + O(H) for `_balancePath`). Space O(H) for path/recursion.
4251
- *
4252
- * @param keyNodeOrEntry - The key, node, or entry to set.
4253
- * @param [value] - The value, if providing just a key.
4254
- * @returns True if the addition was successful, false otherwise.
4255
- */
4838
+ * Sets a new node to the AVL tree and balances the tree path.
4839
+ * @remarks Time O(log N) (O(H) for BST set + O(H) for `_balancePath`). Space O(H) for path/recursion.
4840
+ *
4841
+ * @param keyNodeOrEntry - The key, node, or entry to set.
4842
+ * @param [value] - The value, if providing just a key.
4843
+ * @returns True if the addition was successful, false otherwise.
4844
+
4845
+
4846
+
4847
+
4848
+
4849
+
4850
+
4851
+
4852
+
4853
+
4854
+
4855
+
4856
+
4857
+
4858
+
4859
+
4860
+
4861
+
4862
+
4863
+
4864
+
4865
+
4866
+
4867
+
4868
+
4869
+
4870
+
4871
+
4872
+
4873
+
4874
+
4875
+
4876
+
4877
+
4878
+
4879
+
4880
+ * @example
4881
+ * // Set a key-value pair
4882
+ * const avl = new AVLTree<number, string>();
4883
+ * avl.set(1, 'one');
4884
+ * avl.set(2, 'two');
4885
+ * console.log(avl.get(1)); // 'one';
4886
+ */
4256
4887
  set(keyNodeOrEntry, value) {
4257
4888
  if (keyNodeOrEntry === null) return false;
4258
4889
  const inserted = super.set(keyNodeOrEntry, value);
@@ -4260,12 +4891,51 @@ var AVLTree = class extends BST {
4260
4891
  return inserted;
4261
4892
  }
4262
4893
  /**
4263
- * Deletes a node from the AVL tree and re-balances the tree.
4264
- * @remarks Time O(log N) (O(H) for BST delete + O(H) for `_balancePath`). Space O(H) for path/recursion.
4265
- *
4266
- * @param keyNodeOrEntry - The node to delete.
4267
- * @returns An array containing deletion results.
4268
- */
4894
+ * Deletes a node from the AVL tree and re-balances the tree.
4895
+ * @remarks Time O(log N) (O(H) for BST delete + O(H) for `_balancePath`). Space O(H) for path/recursion.
4896
+ *
4897
+ * @param keyNodeOrEntry - The node to delete.
4898
+ * @returns An array containing deletion results.
4899
+
4900
+
4901
+
4902
+
4903
+
4904
+
4905
+
4906
+
4907
+
4908
+
4909
+
4910
+
4911
+
4912
+
4913
+
4914
+
4915
+
4916
+
4917
+
4918
+
4919
+
4920
+
4921
+
4922
+
4923
+
4924
+
4925
+
4926
+
4927
+
4928
+
4929
+
4930
+
4931
+
4932
+ * @example
4933
+ * // Remove nodes and verify structure
4934
+ * const avl = new AVLTree<number>([5, 3, 7, 1, 4, 6, 8]);
4935
+ * avl.delete(3);
4936
+ * console.log(avl.has(3)); // false;
4937
+ * console.log(avl.size); // 6;
4938
+ */
4269
4939
  delete(keyNodeOrEntry) {
4270
4940
  const deletedResults = super.delete(keyNodeOrEntry);
4271
4941
  for (const { needBalanced } of deletedResults) {
@@ -4276,13 +4946,33 @@ var AVLTree = class extends BST {
4276
4946
  return deletedResults;
4277
4947
  }
4278
4948
  /**
4279
- * Rebuilds the tree to be perfectly balanced.
4280
- * @remarks AVL trees are already height-balanced, but this makes them *perfectly* balanced (minimal height and all leaves at N or N-1).
4281
- * Time O(N) (O(N) for DFS, O(N) for sorted build). Space O(N) for node array and recursion stack.
4282
- *
4283
- * @param [iterationType=this.iterationType] - The traversal method for the initial node export.
4284
- * @returns True if successful, false if the tree was empty.
4285
- */
4949
+ * Rebuilds the tree to be perfectly balanced.
4950
+ * @remarks AVL trees are already height-balanced, but this makes them *perfectly* balanced (minimal height and all leaves at N or N-1).
4951
+ * Time O(N) (O(N) for DFS, O(N) for sorted build). Space O(N) for node array and recursion stack.
4952
+ *
4953
+ * @param [iterationType=this.iterationType] - The traversal method for the initial node export.
4954
+ * @returns True if successful, false if the tree was empty.
4955
+
4956
+
4957
+
4958
+
4959
+
4960
+
4961
+
4962
+
4963
+
4964
+
4965
+
4966
+
4967
+ * @example
4968
+ * // Rebalance the tree
4969
+ * const avl = new AVLTree<number>();
4970
+ * // Insert in sorted order (worst case for BST)
4971
+ * for (let i = 1; i <= 7; i++) avl.add(i);
4972
+ * console.log(avl.isAVLBalanced()); // false;
4973
+ * avl.perfectlyBalance();
4974
+ * console.log(avl.isAVLBalanced()); // true;
4975
+ */
4286
4976
  perfectlyBalance(iterationType = this.iterationType) {
4287
4977
  const nodes = this.dfs((node) => node, "IN", false, this._root, iterationType);
4288
4978
  const n = nodes.length;
@@ -4306,17 +4996,44 @@ var AVLTree = class extends BST {
4306
4996
  return true;
4307
4997
  }
4308
4998
  /**
4309
- * Creates a new AVLTree by mapping each [key, value] pair.
4310
- * @remarks Time O(N log N) (O(N) iteration + O(log M) `set` for each item into the new tree). Space O(N) for the new tree.
4311
- *
4312
- * @template MK - New key type.
4313
- * @template MV - New value type.
4314
- * @template MR - New raw type.
4315
- * @param callback - A function to map each [key, value] pair.
4316
- * @param [options] - Options for the new AVLTree.
4317
- * @param [thisArg] - `this` context for the callback.
4318
- * @returns A new, mapped AVLTree.
4319
- */
4999
+ * Creates a new AVLTree by mapping each [key, value] pair.
5000
+ * @remarks Time O(N log N) (O(N) iteration + O(log M) `set` for each item into the new tree). Space O(N) for the new tree.
5001
+ *
5002
+ * @template MK - New key type.
5003
+ * @template MV - New value type.
5004
+ * @template MR - New raw type.
5005
+ * @param callback - A function to map each [key, value] pair.
5006
+ * @param [options] - Options for the new AVLTree.
5007
+ * @param [thisArg] - `this` context for the callback.
5008
+ * @returns A new, mapped AVLTree.
5009
+
5010
+
5011
+
5012
+
5013
+
5014
+
5015
+
5016
+
5017
+
5018
+
5019
+
5020
+
5021
+
5022
+
5023
+
5024
+
5025
+
5026
+
5027
+
5028
+
5029
+
5030
+
5031
+ * @example
5032
+ * // Transform to new tree
5033
+ * const avl = new AVLTree<number, number>([[1, 10], [2, 20], [3, 30]]);
5034
+ * const doubled = avl.map((value, key) => [key, (value ?? 0) * 2] as [number, number]);
5035
+ * console.log([...doubled.values()]); // [20, 40, 60];
5036
+ */
4320
5037
  map(callback, options, thisArg) {
4321
5038
  const out = this._createLike([], options);
4322
5039
  let index = 0;