trie-typed 2.1.2 → 2.2.1

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 (33) hide show
  1. package/dist/cjs/index.cjs +30 -28
  2. package/dist/cjs/index.cjs.map +1 -1
  3. package/dist/cjs-legacy/index.cjs +795 -0
  4. package/dist/cjs-legacy/index.cjs.map +1 -0
  5. package/dist/esm/index.mjs +30 -28
  6. package/dist/esm/index.mjs.map +1 -1
  7. package/dist/esm-legacy/index.mjs +790 -0
  8. package/dist/esm-legacy/index.mjs.map +1 -0
  9. package/dist/types/data-structures/binary-tree/avl-tree-counter.d.ts +57 -3
  10. package/dist/types/data-structures/binary-tree/avl-tree-multi-map.d.ts +65 -3
  11. package/dist/types/data-structures/binary-tree/avl-tree.d.ts +61 -5
  12. package/dist/types/data-structures/binary-tree/binary-tree.d.ts +1 -0
  13. package/dist/types/data-structures/binary-tree/bst.d.ts +58 -3
  14. package/dist/types/data-structures/binary-tree/red-black-tree.d.ts +59 -4
  15. package/dist/types/data-structures/binary-tree/tree-counter.d.ts +57 -3
  16. package/dist/types/data-structures/binary-tree/tree-multi-map.d.ts +66 -3
  17. package/dist/types/types/data-structures/base/base.d.ts +1 -1
  18. package/package.json +20 -2
  19. package/src/data-structures/base/iterable-entry-base.ts +4 -4
  20. package/src/data-structures/binary-tree/avl-tree-counter.ts +103 -12
  21. package/src/data-structures/binary-tree/avl-tree-multi-map.ts +116 -12
  22. package/src/data-structures/binary-tree/avl-tree.ts +109 -16
  23. package/src/data-structures/binary-tree/binary-tree.ts +3 -2
  24. package/src/data-structures/binary-tree/bst.ts +104 -12
  25. package/src/data-structures/binary-tree/red-black-tree.ts +110 -19
  26. package/src/data-structures/binary-tree/tree-counter.ts +102 -11
  27. package/src/data-structures/binary-tree/tree-multi-map.ts +124 -12
  28. package/src/data-structures/graph/abstract-graph.ts +8 -8
  29. package/src/data-structures/graph/directed-graph.ts +5 -5
  30. package/src/data-structures/graph/undirected-graph.ts +5 -5
  31. package/src/data-structures/hash/hash-map.ts +4 -4
  32. package/src/types/data-structures/base/base.ts +1 -1
  33. package/tsup.node.config.js +40 -6
@@ -1,12 +1,13 @@
1
1
  'use strict';
2
2
 
3
3
  var __defProp = Object.defineProperty;
4
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
5
4
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
6
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
7
5
 
8
6
  // src/data-structures/base/iterable-element-base.ts
9
- var _IterableElementBase = class _IterableElementBase {
7
+ var IterableElementBase = class {
8
+ static {
9
+ __name(this, "IterableElementBase");
10
+ }
10
11
  /**
11
12
  * Create a new iterable base.
12
13
  *
@@ -17,19 +18,19 @@ var _IterableElementBase = class _IterableElementBase {
17
18
  * Time O(1), Space O(1).
18
19
  */
19
20
  constructor(options) {
20
- /**
21
- * The converter used to transform a raw element (`R`) into a public element (`E`).
22
- *
23
- * @remarks
24
- * Time O(1), Space O(1).
25
- */
26
- __publicField(this, "_toElementFn");
27
21
  if (options) {
28
22
  const { toElementFn } = options;
29
23
  if (typeof toElementFn === "function") this._toElementFn = toElementFn;
30
24
  else if (toElementFn) throw new TypeError("toElementFn must be a function type");
31
25
  }
32
26
  }
27
+ /**
28
+ * The converter used to transform a raw element (`R`) into a public element (`E`).
29
+ *
30
+ * @remarks
31
+ * Time O(1), Space O(1).
32
+ */
33
+ _toElementFn;
33
34
  /**
34
35
  * Exposes the current `toElementFn`, if configured.
35
36
  *
@@ -224,24 +225,23 @@ var _IterableElementBase = class _IterableElementBase {
224
225
  console.log(this.toVisual());
225
226
  }
226
227
  };
227
- __name(_IterableElementBase, "IterableElementBase");
228
- var IterableElementBase = _IterableElementBase;
229
228
 
230
229
  // src/data-structures/trie/trie.ts
231
- var _TrieNode = class _TrieNode {
230
+ var TrieNode = class {
231
+ static {
232
+ __name(this, "TrieNode");
233
+ }
232
234
  /**
233
235
  * Create a Trie node with a character key.
234
236
  * @remarks Time O(1), Space O(1)
235
237
  * @returns New TrieNode instance.
236
238
  */
237
239
  constructor(key) {
238
- __publicField(this, "_key");
239
- __publicField(this, "_children");
240
- __publicField(this, "_isEnd");
241
240
  this._key = key;
242
241
  this._isEnd = false;
243
242
  this._children = /* @__PURE__ */ new Map();
244
243
  }
244
+ _key;
245
245
  /**
246
246
  * Get the character key of this node.
247
247
  * @remarks Time O(1), Space O(1)
@@ -259,6 +259,7 @@ var _TrieNode = class _TrieNode {
259
259
  set key(value) {
260
260
  this._key = value;
261
261
  }
262
+ _children;
262
263
  /**
263
264
  * Get the child map of this node.
264
265
  * @remarks Time O(1), Space O(1)
@@ -276,6 +277,7 @@ var _TrieNode = class _TrieNode {
276
277
  set children(value) {
277
278
  this._children = value;
278
279
  }
280
+ _isEnd;
279
281
  /**
280
282
  * Check whether this node marks the end of a word.
281
283
  * @remarks Time O(1), Space O(1)
@@ -294,9 +296,10 @@ var _TrieNode = class _TrieNode {
294
296
  this._isEnd = value;
295
297
  }
296
298
  };
297
- __name(_TrieNode, "TrieNode");
298
- var TrieNode = _TrieNode;
299
- var _Trie = class _Trie extends IterableElementBase {
299
+ var Trie = class extends IterableElementBase {
300
+ static {
301
+ __name(this, "Trie");
302
+ }
300
303
  /**
301
304
  * Create a Trie and optionally bulk-insert words.
302
305
  * @remarks Time O(totalChars), Space O(totalChars)
@@ -306,9 +309,6 @@ var _Trie = class _Trie extends IterableElementBase {
306
309
  */
307
310
  constructor(words = [], options) {
308
311
  super(options);
309
- __publicField(this, "_size", 0);
310
- __publicField(this, "_caseSensitive", true);
311
- __publicField(this, "_root", new TrieNode(""));
312
312
  if (options) {
313
313
  const { caseSensitive } = options;
314
314
  if (caseSensitive !== void 0) this._caseSensitive = caseSensitive;
@@ -317,6 +317,7 @@ var _Trie = class _Trie extends IterableElementBase {
317
317
  this.addMany(words);
318
318
  }
319
319
  }
320
+ _size = 0;
320
321
  /**
321
322
  * Get the number of stored words.
322
323
  * @remarks Time O(1), Space O(1)
@@ -325,6 +326,7 @@ var _Trie = class _Trie extends IterableElementBase {
325
326
  get size() {
326
327
  return this._size;
327
328
  }
329
+ _caseSensitive = true;
328
330
  /**
329
331
  * Get whether comparisons are case-sensitive.
330
332
  * @remarks Time O(1), Space O(1)
@@ -333,6 +335,7 @@ var _Trie = class _Trie extends IterableElementBase {
333
335
  get caseSensitive() {
334
336
  return this._caseSensitive;
335
337
  }
338
+ _root = new TrieNode("");
336
339
  /**
337
340
  * Get the root node.
338
341
  * @remarks Time O(1), Space O(1)
@@ -662,7 +665,7 @@ var _Trie = class _Trie extends IterableElementBase {
662
665
  const next = new Ctor([], {
663
666
  toElementFn: this.toElementFn,
664
667
  caseSensitive: this.caseSensitive,
665
- ...options != null ? options : {}
668
+ ...options ?? {}
666
669
  });
667
670
  return next;
668
671
  }
@@ -718,8 +721,6 @@ var _Trie = class _Trie extends IterableElementBase {
718
721
  return str;
719
722
  }
720
723
  };
721
- __name(_Trie, "Trie");
722
- var Trie = _Trie;
723
724
 
724
725
  // src/utils/utils.ts
725
726
  function isPrimitiveComparable(value) {
@@ -761,7 +762,7 @@ var DFSOperation = /* @__PURE__ */ ((DFSOperation2) => {
761
762
  DFSOperation2[DFSOperation2["PROCESS"] = 1] = "PROCESS";
762
763
  return DFSOperation2;
763
764
  })(DFSOperation || {});
764
- var _Range = class _Range {
765
+ var Range = class {
765
766
  constructor(low, high, includeLow = true, includeHigh = true) {
766
767
  this.low = low;
767
768
  this.high = high;
@@ -770,6 +771,9 @@ var _Range = class _Range {
770
771
  if (!(isComparable(low) && isComparable(high))) throw new RangeError("low or high is not comparable");
771
772
  if (low > high) throw new RangeError("low must be less than or equal to high");
772
773
  }
774
+ static {
775
+ __name(this, "Range");
776
+ }
773
777
  // Determine whether a key is within the range
774
778
  isInRange(key, comparator) {
775
779
  const lowCheck = this.includeLow ? comparator(key, this.low) >= 0 : comparator(key, this.low) > 0;
@@ -777,8 +781,6 @@ var _Range = class _Range {
777
781
  return lowCheck && highCheck;
778
782
  }
779
783
  };
780
- __name(_Range, "Range");
781
- var Range = _Range;
782
784
  /**
783
785
  * data-structure-typed
784
786
  *
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/data-structures/base/iterable-element-base.ts","../../src/data-structures/trie/trie.ts","../../src/utils/utils.ts","../../src/common/index.ts"],"names":["DFSOperation"],"mappings":";;;;;;;;AAaO,IAAe,oBAAA,GAAf,MAAe,oBAAA,CAAiD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAU3D,YAAY,OAAA,EAA4C;AAclE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAA,aAAA,CAAA,IAAA,EAAU,cAAA,CAAA;AAbR,IAAA,IAAI,OAAA,EAAS;AACX,MAAA,MAAM,EAAE,aAAY,GAAI,OAAA;AACxB,MAAA,IAAI,OAAO,WAAA,KAAgB,UAAA,EAAY,IAAA,CAAK,YAAA,GAAe,WAAA;AAAA,WAAA,IAClD,WAAA,EAAa,MAAM,IAAI,SAAA,CAAU,qCAAqC,CAAA;AAAA,IACjF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAiBA,IAAI,WAAA,GAAkD;AACpD,IAAA,OAAO,IAAA,CAAK,YAAA;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWA,EAAE,MAAA,CAAO,QAAQ,CAAA,CAAA,GAAK,IAAA,EAAsC;AAC1D,IAAA,OAAO,IAAA,CAAK,YAAA,CAAa,GAAG,IAAI,CAAA;AAAA,EAClC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,CAAC,MAAA,GAA8B;AAC7B,IAAA,KAAA,MAAW,IAAA,IAAQ,MAAM,MAAM,IAAA;AAAA,EACjC;AAAA;AAAA;AAAA;AAAA;A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AAA;AAChG,IAAA,MAAM,SAAA,GAAY,IAAA,CAAK,WAAA,GAAc,UAAA,CAAW,GAAA,EAAK,IAAA,CAAK,IAAI,CAAA,IAAK,CAAA,GAAI,UAAA,CAAW,GAAA,EAAK,IAAA,CAAK,IAAI,CAAA,GAAI,CAAA;AACpG,IAAA,OAAO,QAAA,IAAY,SAAA;AAAA,EACrB;AACF,CAAA;AAjBsB,MAAA,CAAA,MAAA,EAAA,OAAA,CAAA;AAAf,IAAM,KAAA,GAAN","file":"index.cjs","sourcesContent":["import type { ElementCallback, IterableElementBaseOptions, ReduceElementCallback } from '../../types';\n\n/**\n * Base class that makes a data structure iterable and provides common\n * element-wise utilities (e.g., map/filter/reduce/find).\n *\n * @template E The public element type yielded by the structure.\n * @template R The underlying \"raw\" element type used internally or by converters.\n *\n * @remarks\n * This class implements the JavaScript iteration protocol (via `Symbol.iterator`)\n * and offers array-like helpers with predictable time/space complexity.\n */\nexport abstract class IterableElementBase<E, R> implements Iterable<E> {\n /**\n * Create a new iterable base.\n *\n * @param options Optional behavior overrides. When provided, a `toElementFn`\n * is used to convert a raw element (`R`) into a public element (`E`).\n *\n * @remarks\n * Time O(1), Space O(1).\n */\n protected constructor(options?: IterableElementBaseOptions<E, R>) {\n if (options) {\n const { toElementFn } = options;\n if (typeof toElementFn === 'function') this._toElementFn = toElementFn;\n else if (toElementFn) throw new TypeError('toElementFn must be a function type');\n }\n }\n\n /**\n * The converter used to transform a raw element (`R`) into a public element (`E`).\n *\n * @remarks\n * Time O(1), Space O(1).\n */\n protected _toElementFn?: (rawElement: R) => E;\n\n /**\n * Exposes the current `toElementFn`, if configured.\n *\n * @returns The converter function or `undefined` when not set.\n * @remarks\n * Time O(1), Space O(1).\n */\n get toElementFn(): ((rawElement: R) => E) | undefined {\n return this._toElementFn;\n }\n\n /**\n * Returns an iterator over the structure's elements.\n *\n * @param args Optional iterator arguments forwarded to the internal iterator.\n * @returns An `IterableIterator<E>` that yields the elements in traversal order.\n *\n * @remarks\n * Producing the iterator is O(1); consuming the entire iterator is Time O(n) with O(1) extra space.\n */\n *[Symbol.iterator](...args: unknown[]): IterableIterator<E> {\n yield* this._getIterator(...args);\n }\n\n /**\n * Returns an iterator over the values (alias of the default iterator).\n *\n * @returns An `IterableIterator<E>` over all elements.\n * @remarks\n * Creating the iterator is O(1); full iteration is Time O(n), Space O(1).\n */\n *values(): IterableIterator<E> {\n for (const item of this) yield item;\n }\n\n /**\n * Tests whether all elements satisfy the predicate.\n *\n * @template TReturn\n * @param predicate Function invoked for each element with signature `(value, index, self)`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns `true` if every element passes; otherwise `false`.\n *\n * @remarks\n * Time O(n) in the worst case; may exit early when the first failure is found. Space O(1).\n */\n every(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): boolean {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n if (!predicate(item, index++, this)) return false;\n } else {\n const fn = predicate as (this: unknown, v: E, i: number, self: this) => boolean;\n if (!fn.call(thisArg, item, index++, this)) return false;\n }\n }\n return true;\n }\n\n /**\n * Tests whether at least one element satisfies the predicate.\n *\n * @param predicate Function invoked for each element with signature `(value, index, self)`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns `true` if any element passes; otherwise `false`.\n *\n * @remarks\n * Time O(n) in the worst case; may exit early on first success. Space O(1).\n */\n some(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): boolean {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n if (predicate(item, index++, this)) return true;\n } else {\n const fn = predicate as (this: unknown, v: E, i: number, self: this) => boolean;\n if (fn.call(thisArg, item, index++, this)) return true;\n }\n }\n return false;\n }\n\n /**\n * Invokes a callback for each element in iteration order.\n *\n * @param callbackfn Function invoked per element with signature `(value, index, self)`.\n * @param thisArg Optional `this` binding for the callback.\n * @returns `void`.\n *\n * @remarks\n * Time O(n), Space O(1).\n */\n forEach(callbackfn: ElementCallback<E, R, void>, thisArg?: unknown): void {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n callbackfn(item, index++, this);\n } else {\n const fn = callbackfn as (this: unknown, v: E, i: number, self: this) => void;\n fn.call(thisArg, item, index++, this);\n }\n }\n }\n\n /**\n * Finds the first element that satisfies the predicate and returns it.\n *\n * @overload\n * Finds the first element of type `S` (a subtype of `E`) that satisfies the predicate and returns it.\n * @template S\n * @param predicate Type-guard predicate: `(value, index, self) => value is S`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns The matched element typed as `S`, or `undefined` if not found.\n *\n * @overload\n * @param predicate Boolean predicate: `(value, index, self) => boolean`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns The first matching element as `E`, or `undefined` if not found.\n *\n * @remarks\n * Time O(n) in the worst case; may exit early on the first match. Space O(1).\n */\n find<S extends E>(predicate: ElementCallback<E, R, S>, thisArg?: unknown): S | undefined;\n find(predicate: ElementCallback<E, R, unknown>, thisArg?: unknown): E | undefined;\n\n // Implementation signature\n find(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): E | undefined {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n if (predicate(item, index++, this)) return item;\n } else {\n const fn = predicate as (this: unknown, v: E, i: number, self: this) => boolean;\n if (fn.call(thisArg, item, index++, this)) return item;\n }\n }\n return;\n }\n\n /**\n * Checks whether a strictly-equal element exists in the structure.\n *\n * @param element The element to test with `===` equality.\n * @returns `true` if an equal element is found; otherwise `false`.\n *\n * @remarks\n * Time O(n) in the worst case. Space O(1).\n */\n has(element: E): boolean {\n for (const ele of this) if (ele === element) return true;\n return false;\n }\n\n reduce(callbackfn: ReduceElementCallback<E, R>): E;\n reduce(callbackfn: ReduceElementCallback<E, R>, initialValue: E): E;\n reduce<U>(callbackfn: ReduceElementCallback<E, R, U>, initialValue: U): U;\n\n /**\n * Reduces all elements to a single accumulated value.\n *\n * @overload\n * @param callbackfn Reducer of signature `(acc, value, index, self) => nextAcc`. The first element is used as the initial accumulator.\n * @returns The final accumulated value typed as `E`.\n *\n * @overload\n * @param callbackfn Reducer of signature `(acc, value, index, self) => nextAcc`.\n * @param initialValue The initial accumulator value of type `E`.\n * @returns The final accumulated value typed as `E`.\n *\n * @overload\n * @template U The accumulator type when it differs from `E`.\n * @param callbackfn Reducer of signature `(acc: U, value, index, self) => U`.\n * @param initialValue The initial accumulator value of type `U`.\n * @returns The final accumulated value typed as `U`.\n *\n * @remarks\n * Time O(n), Space O(1). Throws if called on an empty structure without `initialValue`.\n */\n reduce<U>(callbackfn: ReduceElementCallback<E, R, U>, initialValue?: U): U {\n let index = 0;\n const iter = this[Symbol.iterator]();\n let acc: U;\n\n if (arguments.length >= 2) {\n acc = initialValue as U;\n } else {\n const first = iter.next();\n if (first.done) throw new TypeError('Reduce of empty structure with no initial value');\n acc = first.value as unknown as U;\n index = 1;\n }\n\n for (const value of iter as unknown as Iterable<E>) {\n acc = callbackfn(acc, value, index++, this);\n }\n return acc;\n }\n\n /**\n * Materializes the elements into a new array.\n *\n * @returns A shallow array copy of the iteration order.\n * @remarks\n * Time O(n), Space O(n).\n */\n toArray(): E[] {\n return [...this];\n }\n\n /**\n * Returns a representation of the structure suitable for quick visualization.\n * Defaults to an array of elements; subclasses may override to provide richer visuals.\n *\n * @returns A visual representation (array by default).\n * @remarks\n * Time O(n), Space O(n).\n */\n toVisual(): E[] {\n return [...this];\n }\n\n /**\n * Prints `toVisual()` to the console. Intended for quick debugging.\n *\n * @returns `void`.\n * @remarks\n * Time O(n) due to materialization, Space O(n) for the intermediate representation.\n */\n print(): void {\n console.log(this.toVisual());\n }\n\n /**\n * Indicates whether the structure currently contains no elements.\n *\n * @returns `true` if empty; otherwise `false`.\n * @remarks\n * Expected Time O(1), Space O(1) for most implementations.\n */\n abstract isEmpty(): boolean;\n\n /**\n * Removes all elements from the structure.\n *\n * @returns `void`.\n * @remarks\n * Expected Time O(1) or O(n) depending on the implementation; Space O(1).\n */\n abstract clear(): void;\n\n /**\n * Creates a structural copy with the same element values and configuration.\n *\n * @returns A clone of the current instance (same concrete type).\n * @remarks\n * Expected Time O(n) to copy elements; Space O(n).\n */\n abstract clone(): this;\n\n /**\n * Maps each element to a new element and returns a new iterable structure.\n *\n * @template EM The mapped element type.\n * @template RM The mapped raw element type used internally by the target structure.\n * @param callback Function with signature `(value, index, self) => mapped`.\n * @param options Optional options for the returned structure, including its `toElementFn`.\n * @param thisArg Optional `this` binding for the callback.\n * @returns A new `IterableElementBase<EM, RM>` containing mapped elements.\n *\n * @remarks\n * Time O(n), Space O(n).\n */\n abstract map<EM, RM>(\n callback: ElementCallback<E, R, EM>,\n options?: IterableElementBaseOptions<EM, RM>,\n thisArg?: unknown\n ): IterableElementBase<EM, RM>;\n\n /**\n * Maps each element to the same element type and returns the same concrete structure type.\n *\n * @param callback Function with signature `(value, index, self) => mappedValue`.\n * @param thisArg Optional `this` binding for the callback.\n * @returns A new instance of the same concrete type with mapped elements.\n *\n * @remarks\n * Time O(n), Space O(n).\n */\n abstract mapSame(callback: ElementCallback<E, R, E>, thisArg?: unknown): this;\n\n /**\n * Filters elements using the provided predicate and returns the same concrete structure type.\n *\n * @param predicate Function with signature `(value, index, self) => boolean`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns A new instance of the same concrete type containing only elements that pass the predicate.\n *\n * @remarks\n * Time O(n), Space O(k) where `k` is the number of kept elements.\n */\n abstract filter(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): this;\n\n /**\n * Internal iterator factory used by the default iterator.\n *\n * @param args Optional iterator arguments.\n * @returns An iterator over elements.\n *\n * @remarks\n * Implementations should yield in O(1) per element with O(1) extra space when possible.\n */\n protected abstract _getIterator(...args: unknown[]): IterableIterator<E>;\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type { ElementCallback, TrieOptions } from '../../types';\nimport { IterableElementBase } from '../base';\n\n/**\n * Node used by Trie to store one character and its children.\n * @remarks Time O(1), Space O(1)\n */\nexport class TrieNode {\n /**\n * Create a Trie node with a character key.\n * @remarks Time O(1), Space O(1)\n * @returns New TrieNode instance.\n */\n\n constructor(key: string) {\n this._key = key;\n this._isEnd = false;\n this._children = new Map<string, TrieNode>();\n }\n\n protected _key: string;\n\n /**\n * Get the character key of this node.\n * @remarks Time O(1), Space O(1)\n * @returns Character key string.\n */\n\n get key(): string {\n return this._key;\n }\n\n /**\n * Set the character key of this node.\n * @remarks Time O(1), Space O(1)\n * @param value - New character key.\n * @returns void\n */\n\n set key(value: string) {\n this._key = value;\n }\n\n protected _children: Map<string, TrieNode>;\n\n /**\n * Get the child map of this node.\n * @remarks Time O(1), Space O(1)\n * @returns Map from character to child node.\n */\n\n get children(): Map<string, TrieNode> {\n return this._children;\n }\n\n /**\n * Replace the child map of this node.\n * @remarks Time O(1), Space O(1)\n * @param value - New map of character → node.\n * @returns void\n */\n\n set children(value: Map<string, TrieNode>) {\n this._children = value;\n }\n\n protected _isEnd: boolean;\n\n /**\n * Check whether this node marks the end of a word.\n * @remarks Time O(1), Space O(1)\n * @returns True if this node ends a word.\n */\n\n get isEnd(): boolean {\n return this._isEnd;\n }\n\n /**\n * Mark this node as the end of a word or not.\n * @remarks Time O(1), Space O(1)\n * @param value - Whether this node ends a word.\n * @returns void\n */\n\n set isEnd(value: boolean) {\n this._isEnd = value;\n }\n}\n\n/**\n * Prefix tree (Trie) for fast prefix queries and word storage.\n * @remarks Time O(1), Space O(1)\n * @template R\n * 1. Node Structure: Each node in a Trie represents a string (or a part of a string). The root node typically represents an empty string.\n * 2. Child Node Relationship: Each node's children represent the strings that can be formed by adding one character to the string at the current node. For example, if a node represents the string 'ca', one of its children might represent 'cat'.\n * 3. Fast Retrieval: Trie allows retrieval in O(m) time complexity, where m is the length of the string to be searched.\n * 4. Space Efficiency: Trie can store a large number of strings very space-efficiently, especially when these strings share common prefixes.\n * 5. Autocomplete and Prediction: Trie can be used for implementing autocomplete and word prediction features, as it can quickly find all strings with a common prefix.\n * 6. Sorting: Trie can be used to sort a set of strings in alphabetical order.\n * 7. String Retrieval: For example, searching for a specific string in a large set of strings.\n * 8. Autocomplete: Providing recommended words or phrases as a user types.\n * 9. Spell Check: Checking the spelling of words.\n * 10. IP Routing: Used in certain types of IP routing algorithms.\n * 11. Text Word Frequency Count: Counting and storing the frequency of words in a large amount of text data.\n * @example\n * // Autocomplete: Prefix validation and checking\n * const autocomplete = new Trie<string>(['gmail.com', 'gmail.co.nz', 'gmail.co.jp', 'yahoo.com', 'outlook.com']);\n *\n * // Get all completions for a prefix\n * const gmailCompletions = autocomplete.getWords('gmail');\n * console.log(gmailCompletions); // ['gmail.com', 'gmail.co.nz', 'gmail.co.jp']\n * @example\n * // File System Path Operations\n * const fileSystem = new Trie<string>([\n * '/home/user/documents/file1.txt',\n * '/home/user/documents/file2.txt',\n * '/home/user/pictures/photo.jpg',\n * '/home/user/pictures/vacation/',\n * '/home/user/downloads'\n * ]);\n *\n * // Find common directory prefix\n * console.log(fileSystem.getLongestCommonPrefix()); // '/home/user/'\n *\n * // List all files in a directory\n * const documentsFiles = fileSystem.getWords('/home/user/documents/');\n * console.log(documentsFiles); // ['/home/user/documents/file1.txt', '/home/user/documents/file2.txt']\n * @example\n * // Autocomplete: Basic word suggestions\n * // Create a trie for autocomplete\n * const autocomplete = new Trie<string>([\n * 'function',\n * 'functional',\n * 'functions',\n * 'class',\n * 'classes',\n * 'classical',\n * 'closure',\n * 'const',\n * 'constructor'\n * ]);\n *\n * // Test autocomplete with different prefixes\n * console.log(autocomplete.getWords('fun')); // ['functional', 'functions', 'function']\n * console.log(autocomplete.getWords('cla')); // ['classes', 'classical', 'class']\n * console.log(autocomplete.getWords('con')); // ['constructor', 'const']\n *\n * // Test with non-matching prefix\n * console.log(autocomplete.getWords('xyz')); // []\n * @example\n * // Dictionary: Case-insensitive word lookup\n * // Create a case-insensitive dictionary\n * const dictionary = new Trie<string>([], { caseSensitive: false });\n *\n * // Add words with mixed casing\n * dictionary.add('Hello');\n * dictionary.add('WORLD');\n * dictionary.add('JavaScript');\n *\n * // Test lookups with different casings\n * console.log(dictionary.has('hello')); // true\n * console.log(dictionary.has('HELLO')); // true\n * console.log(dictionary.has('Hello')); // true\n * console.log(dictionary.has('javascript')); // true\n * console.log(dictionary.has('JAVASCRIPT')); // true\n * @example\n * // IP Address Routing Table\n * // Add IP address prefixes and their corresponding routes\n * const routes = {\n * '192.168.1': 'LAN_SUBNET_1',\n * '192.168.2': 'LAN_SUBNET_2',\n * '10.0.0': 'PRIVATE_NETWORK_1',\n * '10.0.1': 'PRIVATE_NETWORK_2'\n * };\n *\n * const ipRoutingTable = new Trie<string>(Object.keys(routes));\n *\n * // Check IP address prefix matching\n * console.log(ipRoutingTable.hasPrefix('192.168.1')); // true\n * console.log(ipRoutingTable.hasPrefix('192.168.2')); // true\n *\n * // Validate IP address belongs to subnet\n * const ip = '192.168.1.100';\n * const subnet = ip.split('.').slice(0, 3).join('.');\n * console.log(ipRoutingTable.hasPrefix(subnet)); // true\n */\nexport class Trie<R = any> extends IterableElementBase<string, R> {\n /**\n * Create a Trie and optionally bulk-insert words.\n * @remarks Time O(totalChars), Space O(totalChars)\n * @param [words] - Iterable of strings (or raw records if toElementFn is provided).\n * @param [options] - Options such as toElementFn and caseSensitive.\n * @returns New Trie instance.\n */\n\n constructor(words: Iterable<string> | Iterable<R> = [], options?: TrieOptions<R>) {\n super(options);\n if (options) {\n const { caseSensitive } = options;\n if (caseSensitive !== undefined) this._caseSensitive = caseSensitive;\n }\n if (words) {\n this.addMany(words);\n }\n }\n\n protected _size: number = 0;\n\n /**\n * Get the number of stored words.\n * @remarks Time O(1), Space O(1)\n * @returns Word count.\n */\n\n get size(): number {\n return this._size;\n }\n\n protected _caseSensitive: boolean = true;\n\n /**\n * Get whether comparisons are case-sensitive.\n * @remarks Time O(1), Space O(1)\n * @returns True if case-sensitive.\n */\n\n get caseSensitive(): boolean {\n return this._caseSensitive;\n }\n\n protected _root: TrieNode = new TrieNode('');\n\n /**\n * Get the root node.\n * @remarks Time O(1), Space O(1)\n * @returns Root TrieNode.\n */\n\n get root() {\n return this._root;\n }\n\n /**\n * (Protected) Get total count for base class iteration.\n * @remarks Time O(1), Space O(1)\n * @returns Total number of elements.\n */\n\n protected get _total() {\n return this._size;\n }\n\n /**\n * Insert one word into the trie.\n * @remarks Time O(L), Space O(L)\n * @param word - Word to insert.\n * @returns True if the word was newly added.\n */\n\n add(word: string): boolean {\n word = this._caseProcess(word);\n let cur = this.root;\n let isNewWord = false;\n for (const c of word) {\n let nodeC = cur.children.get(c);\n if (!nodeC) {\n nodeC = new TrieNode(c);\n cur.children.set(c, nodeC);\n }\n cur = nodeC;\n }\n if (!cur.isEnd) {\n isNewWord = true;\n cur.isEnd = true;\n this._size++;\n }\n return isNewWord;\n }\n\n /**\n * Insert many words from an iterable.\n * @remarks Time O(ΣL), Space O(ΣL)\n * @param words - Iterable of strings (or raw records if toElementFn is provided).\n * @returns Array of per-word 'added' flags.\n */\n\n addMany(words: Iterable<string> | Iterable<R>): boolean[] {\n const ans: boolean[] = [];\n for (const word of words) {\n if (this.toElementFn) {\n ans.push(this.add(this.toElementFn(word as R)));\n } else {\n ans.push(this.add(word as string));\n }\n }\n return ans;\n }\n\n /**\n * Check whether a word exists.\n * @remarks Time O(L), Space O(1)\n * @param word - Word to search for.\n * @returns True if present.\n */\n\n override has(word: string): boolean {\n word = this._caseProcess(word);\n let cur = this.root;\n for (const c of word) {\n const nodeC = cur.children.get(c);\n if (!nodeC) return false;\n cur = nodeC;\n }\n return cur.isEnd;\n }\n\n /**\n * Check whether the trie is empty.\n * @remarks Time O(1), Space O(1)\n * @returns True if size is 0.\n */\n\n isEmpty(): boolean {\n return this._size === 0;\n }\n\n /**\n * Remove all words and reset to a fresh root.\n * @remarks Time O(1), Space O(1)\n * @returns void\n */\n\n clear(): void {\n this._size = 0;\n this._root = new TrieNode('');\n }\n\n /**\n * Delete one word if present.\n * @remarks Time O(L), Space O(1)\n * @param word - Word to delete.\n * @returns True if a word was removed.\n */\n\n delete(word: string): boolean {\n word = this._caseProcess(word);\n let isDeleted = false;\n const dfs = (cur: TrieNode, i: number): boolean => {\n const char = word[i];\n const child = cur.children.get(char);\n if (child) {\n if (i === word.length - 1) {\n if (child.isEnd) {\n if (child.children.size > 0) {\n child.isEnd = false;\n } else {\n cur.children.delete(char);\n }\n isDeleted = true;\n return true;\n }\n return false;\n }\n const res = dfs(child, i + 1);\n if (res && !cur.isEnd && child.children.size === 0) {\n cur.children.delete(char);\n return true;\n }\n return false;\n }\n return false;\n };\n\n dfs(this.root, 0);\n if (isDeleted) {\n this._size--;\n }\n return isDeleted;\n }\n\n /**\n * Compute the height (max depth) of the trie.\n * @remarks Time O(N), Space O(H)\n * @returns Maximum depth from root to a leaf.\n */\n\n getHeight(): number {\n const startNode = this.root;\n let maxDepth = 0;\n if (startNode) {\n const bfs = (node: TrieNode, level: number) => {\n if (level > maxDepth) {\n maxDepth = level;\n }\n const { children } = node;\n if (children) {\n for (const child of children.entries()) {\n bfs(child[1], level + 1);\n }\n }\n };\n bfs(startNode, 0);\n }\n return maxDepth;\n }\n\n /**\n * Check whether input is a proper prefix of at least one word.\n * @remarks Time O(L), Space O(1)\n * @param input - String to test as prefix.\n * @returns True if input is a prefix but not a full word.\n */\n\n hasPurePrefix(input: string): boolean {\n input = this._caseProcess(input);\n let cur = this.root;\n for (const c of input) {\n const nodeC = cur.children.get(c);\n if (!nodeC) return false;\n cur = nodeC;\n }\n return !cur.isEnd;\n }\n\n /**\n * Check whether any word starts with input.\n * @remarks Time O(L), Space O(1)\n * @param input - String to test as prefix.\n * @returns True if input matches a path from root.\n */\n\n hasPrefix(input: string): boolean {\n input = this._caseProcess(input);\n let cur = this.root;\n for (const c of input) {\n const nodeC = cur.children.get(c);\n if (!nodeC) return false;\n cur = nodeC;\n }\n return true;\n }\n\n /**\n * Check whether the trie’s longest common prefix equals input.\n * @remarks Time O(min(H,L)), Space O(1)\n * @param input - Candidate longest common prefix.\n * @returns True if input equals the common prefix.\n */\n\n hasCommonPrefix(input: string): boolean {\n input = this._caseProcess(input);\n let commonPre = '';\n const dfs = (cur: TrieNode) => {\n commonPre += cur.key;\n if (commonPre === input) return;\n if (cur.isEnd) return;\n if (cur && cur.children && cur.children.size === 1) dfs(Array.from(cur.children.values())[0]);\n else return;\n };\n dfs(this.root);\n return commonPre === input;\n }\n\n /**\n * Return the longest common prefix among all words.\n * @remarks Time O(H), Space O(1)\n * @returns The longest common prefix string.\n */\n\n getLongestCommonPrefix(): string {\n let commonPre = '';\n const dfs = (cur: TrieNode) => {\n commonPre += cur.key;\n if (cur.isEnd) return;\n if (cur && cur.children && cur.children.size === 1) dfs(Array.from(cur.children.values())[0]);\n else return;\n };\n dfs(this.root);\n return commonPre;\n }\n\n /**\n * Collect words under a prefix up to a maximum count.\n * @remarks Time O(K·L), Space O(K·L)\n * @param [prefix] - Prefix to match; default empty string for root.\n * @param [max] - Maximum number of words to return; default is Number.MAX_SAFE_INTEGER.\n * @param [isAllWhenEmptyPrefix] - When true, collect from root even if prefix is empty.\n * @returns Array of collected words (at most max).\n */\n\n getWords(prefix = '', max = Number.MAX_SAFE_INTEGER, isAllWhenEmptyPrefix = false): string[] {\n prefix = this._caseProcess(prefix);\n const words: string[] = [];\n let found = 0;\n\n function dfs(node: TrieNode, word: string) {\n for (const char of node.children.keys()) {\n const charNode = node.children.get(char);\n if (charNode !== undefined) {\n dfs(charNode, word.concat(char));\n }\n }\n if (node.isEnd) {\n if (found > max - 1) return;\n words.push(word);\n found++;\n }\n }\n\n let startNode = this.root;\n\n if (prefix) {\n for (const c of prefix) {\n const nodeC = startNode.children.get(c);\n if (nodeC) {\n startNode = nodeC;\n } else {\n return [];\n }\n }\n }\n\n if (isAllWhenEmptyPrefix || startNode !== this.root) dfs(startNode, prefix);\n\n return words;\n }\n\n /**\n * Deep clone this trie by iterating and inserting all words.\n * @remarks Time O(ΣL), Space O(ΣL)\n * @returns A new trie with the same words and options.\n */\n\n clone(): this {\n const next = this._createInstance();\n for (const x of this) next.add(x);\n return next;\n }\n\n /**\n * Filter words into a new trie of the same class.\n * @remarks Time O(ΣL), Space O(ΣL)\n * @param predicate - Predicate (word, index, trie) → boolean to keep word.\n * @param [thisArg] - Value for `this` inside the predicate.\n * @returns A new trie containing words that satisfy the predicate.\n */\n\n filter(predicate: ElementCallback<string, R, boolean>, thisArg?: any): this {\n const results = this._createInstance();\n let index = 0;\n for (const word of this) {\n if (predicate.call(thisArg, word, index, this)) {\n results.add(word);\n }\n index++;\n }\n return results;\n }\n\n map<RM>(callback: ElementCallback<string, R, string>, options?: TrieOptions<RM>, thisArg?: any): Trie<RM>;\n\n /**\n * Map words into a new trie (possibly different record type).\n * @remarks Time O(ΣL), Space O(ΣL)\n * @template EM\n * @template RM\n * @param callback - Mapping function (word, index, trie) → newWord (string).\n * @param [options] - Options for the output trie (e.g., toElementFn, caseSensitive).\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new Trie constructed from mapped words.\n */\n\n map<EM, RM>(\n callback: ElementCallback<string, R, EM>,\n options?: TrieOptions<RM>,\n thisArg?: any\n ): IterableElementBase<EM, RM>;\n\n map<EM, RM>(callback: ElementCallback<string, R, EM>, options?: TrieOptions<RM>, thisArg?: any): any {\n const newTrie = this._createLike<RM>([], options);\n let i = 0;\n for (const x of this) {\n const v = thisArg === undefined ? callback(x, i++, this) : callback.call(thisArg, x, i++, this);\n if (typeof v !== 'string') {\n throw new TypeError(`Trie.map callback must return string; got ${typeof v}`);\n }\n newTrie.add(v);\n }\n return newTrie;\n }\n\n /**\n * Map words into a new trie of the same element type.\n * @remarks Time O(ΣL), Space O(ΣL)\n * @param callback - Mapping function (word, index, trie) → string.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new trie with mapped words.\n */\n\n mapSame(callback: ElementCallback<string, R, string>, thisArg?: any): this {\n const next = this._createInstance();\n let i = 0;\n for (const key of this) {\n const mapped = thisArg === undefined ? callback(key, i++, this) : callback.call(thisArg, key, i++, this);\n next.add(mapped);\n }\n return next;\n }\n\n /**\n * (Protected) Create an empty instance of the same concrete class.\n * @remarks Time O(1), Space O(1)\n * @param [options] - Options forwarded to the constructor.\n * @returns An empty like-kind trie instance.\n */\n\n protected _createInstance(options?: TrieOptions<R>): this {\n const Ctor: any = this.constructor;\n const next: any = new Ctor([], {\n toElementFn: this.toElementFn,\n caseSensitive: this.caseSensitive,\n ...(options ?? {})\n });\n return next as this;\n }\n\n /**\n * (Protected) Create a like-kind trie and seed it from an iterable.\n * @remarks Time O(ΣL), Space O(ΣL)\n * @template RM\n * @param [elements] - Iterable used to seed the new trie.\n * @param [options] - Options forwarded to the constructor.\n * @returns A like-kind Trie instance.\n */\n\n protected _createLike<RM>(elements: Iterable<string> | Iterable<RM> = [], options?: TrieOptions<RM>): Trie<RM> {\n const Ctor: any = this.constructor;\n return new Ctor(elements, options) as Trie<RM>;\n }\n\n /**\n * (Protected) Spawn an empty like-kind trie instance.\n * @remarks Time O(1), Space O(1)\n * @template RM\n * @param [options] - Options forwarded to the constructor.\n * @returns An empty like-kind Trie instance.\n */\n\n protected _spawnLike<RM>(options?: TrieOptions<RM>): Trie<RM> {\n return this._createLike<RM>([], options);\n }\n\n /**\n * (Protected) Iterate all words in lexicographic order of edges.\n * @remarks Time O(ΣL), Space O(H)\n * @returns Iterator of words.\n */\n\n protected *_getIterator(): IterableIterator<string> {\n function* _dfs(node: TrieNode, path: string): IterableIterator<string> {\n if (node.isEnd) {\n yield path;\n }\n for (const [char, childNode] of node.children) {\n yield* _dfs(childNode, path + char);\n }\n }\n\n yield* _dfs(this.root, '');\n }\n\n /**\n * (Protected) Normalize a string according to case sensitivity.\n * @remarks Time O(L), Space O(L)\n * @param str - Input string to normalize.\n * @returns Normalized string based on caseSensitive.\n */\n\n protected _caseProcess(str: string) {\n if (!this._caseSensitive) {\n str = str.toLowerCase();\n }\n return str;\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\nimport type { Comparable, ComparablePrimitive, Trampoline, TrampolineThunk } from '../types';\n\n/**\n * The function generates a random UUID (Universally Unique Identifier) in TypeScript.\n * @returns A randomly generated UUID (Universally Unique Identifier) in the format\n * 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' where each 'x' is replaced with a random hexadecimal\n * character.\n */\nexport const uuidV4 = function () {\n return 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'.replace(/[x]/g, function (c) {\n const r = (Math.random() * 16) | 0,\n v = c == 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n};\n\n/**\n * The `arrayRemove` function removes elements from an array based on a specified predicate function\n * and returns the removed elements.\n * @param {T[]} array - An array of elements that you want to filter based on the provided predicate\n * function.\n * @param predicate - The `predicate` parameter is a function that takes three arguments:\n * @returns The `arrayRemove` function returns an array containing the elements that satisfy the given\n * `predicate` function.\n */\nexport const arrayRemove = function <T>(array: T[], predicate: (item: T, index: number, array: T[]) => boolean): T[] {\n let i = -1,\n len = array ? array.length : 0;\n const result = [];\n\n while (++i < len) {\n const value = array[i];\n if (predicate(value, i, array)) {\n result.push(value);\n Array.prototype.splice.call(array, i--, 1);\n len--;\n }\n }\n\n return result;\n};\n\n/**\n * The function `getMSB` returns the most significant bit of a given number.\n * @param {number} value - The `value` parameter is a number for which we want to find the position of\n * the Most Significant Bit (MSB). The function `getMSB` takes this number as input and calculates the\n * position of the MSB in its binary representation.\n * @returns The function `getMSB` returns the most significant bit (MSB) of the input `value`. If the\n * input value is less than or equal to 0, it returns 0. Otherwise, it calculates the position of the\n * MSB using the `Math.clz32` function and bitwise left shifts 1 to that position.\n */\nexport const getMSB = (value: number): number => {\n if (value <= 0) {\n return 0;\n }\n return 1 << (31 - Math.clz32(value));\n};\n\n/**\n * The `rangeCheck` function in TypeScript is used to validate if an index is within a specified range\n * and throws a `RangeError` with a custom message if it is out of bounds.\n * @param {number} index - The `index` parameter represents the value that you want to check if it\n * falls within a specified range.\n * @param {number} min - The `min` parameter represents the minimum value that the `index` should be\n * compared against in the `rangeCheck` function.\n * @param {number} max - The `max` parameter in the `rangeCheck` function represents the maximum value\n * that the `index` parameter is allowed to have. If the `index` is greater than this `max` value, a\n * `RangeError` will be thrown.\n * @param [message=Index out of bounds.] - The `message` parameter is a string that represents the\n * error message to be thrown if the index is out of bounds. By default, if no message is provided when\n * calling the `rangeCheck` function, the message \"Index out of bounds.\" will be used.\n */\nexport const rangeCheck = (index: number, min: number, max: number, message = 'Index out of bounds.'): void => {\n if (index < min || index > max) throw new RangeError(message);\n};\n\n/**\n * The function `throwRangeError` throws a RangeError with a custom message if called.\n * @param [message=The value is off-limits.] - The `message` parameter is a string that represents the\n * error message to be displayed when a `RangeError` is thrown. If no message is provided, the default\n * message is 'The value is off-limits.'.\n */\nexport const throwRangeError = (message = 'The value is off-limits.'): void => {\n throw new RangeError(message);\n};\n\n/**\n * The function `isWeakKey` checks if the input is an object or a function in TypeScript.\n * @param {unknown} input - The `input` parameter in the `isWeakKey` function is of type `unknown`,\n * which means it can be any type. The function checks if the `input` is an object (excluding `null`)\n * or a function, and returns a boolean indicating whether the `input` is a weak\n * @returns The function `isWeakKey` returns a boolean value indicating whether the input is an object\n * or a function.\n */\nexport const isWeakKey = (input: unknown): input is object => {\n const inputType = typeof input;\n return (inputType === 'object' && input !== null) || inputType === 'function';\n};\n\n/**\n * The function `calcMinUnitsRequired` calculates the minimum number of units required to accommodate a\n * given total quantity based on a specified unit size.\n * @param {number} totalQuantity - The `totalQuantity` parameter represents the total quantity of items\n * that need to be processed or handled.\n * @param {number} unitSize - The `unitSize` parameter represents the size of each unit or package. It\n * is used in the `calcMinUnitsRequired` function to calculate the minimum number of units required to\n * accommodate a total quantity of items.\n */\nexport const calcMinUnitsRequired = (totalQuantity: number, unitSize: number) =>\n Math.floor((totalQuantity + unitSize - 1) / unitSize);\n\n/**\n * The `roundFixed` function in TypeScript rounds a number to a specified number of decimal places.\n * @param {number} num - The `num` parameter is a number that you want to round to a certain number of\n * decimal places.\n * @param {number} [digit=10] - The `digit` parameter in the `roundFixed` function specifies the number\n * of decimal places to round the number to. By default, it is set to 10 if not provided explicitly.\n * @returns The function `roundFixed` returns a number that is rounded to the specified number of\n * decimal places (default is 10 decimal places).\n */\nexport const roundFixed = (num: number, digit: number = 10) => {\n const multiplier = Math.pow(10, digit);\n return Math.round(num * multiplier) / multiplier;\n};\n\n/**\n * The function `isPrimitiveComparable` checks if a value is a primitive type that can be compared.\n * @param {unknown} value - The `value` parameter in the `isPrimitiveComparable` function is of type\n * `unknown`, which means it can be any type. The function checks if the `value` is a primitive type\n * that can be compared, such as number, bigint, string, or boolean.\n * @returns The function `isPrimitiveComparable` returns a boolean value indicating whether the input\n * `value` is a primitive value that can be compared using standard comparison operators (<, >, <=,\n * >=).\n */\nfunction isPrimitiveComparable(value: unknown): value is ComparablePrimitive {\n const valueType = typeof value;\n if (valueType === 'number') return true;\n // if (valueType === 'number') return !Number.isNaN(value);\n return valueType === 'bigint' || valueType === 'string' || valueType === 'boolean';\n}\n\n/**\n * The function `tryObjectToPrimitive` attempts to convert an object to a comparable primitive value by\n * first checking the `valueOf` method and then the `toString` method.\n * @param {object} obj - The `obj` parameter in the `tryObjectToPrimitive` function is an object that\n * you want to convert to a primitive value. The function attempts to convert the object to a primitive\n * value by first checking if the object has a `valueOf` method. If the `valueOf` method exists, it\n * @returns The function `tryObjectToPrimitive` returns a value of type `ComparablePrimitive` if a\n * primitive comparable value is found within the object, or a string value if the object has a custom\n * `toString` method that does not return `'[object Object]'`. If neither condition is met, the\n * function returns `null`.\n */\nfunction tryObjectToPrimitive(obj: object): ComparablePrimitive | null {\n if (typeof obj.valueOf === 'function') {\n const valueOfResult = obj.valueOf();\n if (valueOfResult !== obj) {\n if (isPrimitiveComparable(valueOfResult)) return valueOfResult;\n if (typeof valueOfResult === 'object' && valueOfResult !== null) return tryObjectToPrimitive(valueOfResult);\n }\n }\n if (typeof obj.toString === 'function') {\n const stringResult = obj.toString();\n if (stringResult !== '[object Object]') return stringResult;\n }\n return null;\n}\n\n/**\n * The function `isComparable` in TypeScript checks if a value is comparable, handling primitive values\n * and objects with optional force comparison.\n * @param {unknown} value - The `value` parameter in the `isComparable` function represents the value\n * that you want to check if it is comparable. It can be of any type (`unknown`), and the function will\n * determine if it is comparable based on certain conditions.\n * @param [isForceObjectComparable=false] - The `isForceObjectComparable` parameter in the\n * `isComparable` function is a boolean flag that determines whether to treat non-primitive values as\n * comparable objects. When set to `true`, it forces the function to consider non-primitive values as\n * comparable objects, regardless of their type.\n * @returns The function `isComparable` returns a boolean value indicating whether the `value` is\n * considered comparable or not.\n */\nexport function isComparable(value: unknown, isForceObjectComparable = false): value is Comparable {\n if (value === null || value === undefined) return false;\n if (isPrimitiveComparable(value)) return true;\n\n if (typeof value !== 'object') return false;\n if (value instanceof Date) return true;\n // if (value instanceof Date) return !Number.isNaN(value.getTime());\n if (isForceObjectComparable) return true;\n const comparableValue = tryObjectToPrimitive(value);\n if (comparableValue === null || comparableValue === undefined) return false;\n return isPrimitiveComparable(comparableValue);\n}\n\n/**\n * Creates a trampoline thunk object.\n *\n * A \"thunk\" is a deferred computation — instead of performing a recursive call immediately,\n * it wraps the next step of the computation in a function. This allows recursive processes\n * to be executed iteratively, preventing stack overflows.\n *\n * @template T - The type of the final computation result.\n * @param computation - A function that, when executed, returns the next trampoline step.\n * @returns A TrampolineThunk object containing the deferred computation.\n */\nexport const makeTrampolineThunk = <T>(computation: () => Trampoline<T>): TrampolineThunk<T> => ({\n isThunk: true, // Marker indicating this is a thunk\n fn: computation // The deferred computation function\n});\n\n/**\n * Type guard to check whether a given value is a TrampolineThunk.\n *\n * This function is used to distinguish between a final computation result (value)\n * and a deferred computation (thunk).\n *\n * @template T - The type of the value being checked.\n * @param value - The value to test.\n * @returns True if the value is a valid TrampolineThunk, false otherwise.\n */\nexport const isTrampolineThunk = <T>(value: Trampoline<T>): value is TrampolineThunk<T> =>\n typeof value === 'object' && // Must be an object\n value !== null && // Must not be null\n 'isThunk' in value && // Must have the 'isThunk' property\n value.isThunk; // The flag must be true\n\n/**\n * Executes a trampoline computation until a final (non-thunk) result is obtained.\n *\n * The trampoline function repeatedly invokes the deferred computations (thunks)\n * in an iterative loop. This avoids deep recursive calls and prevents stack overflow,\n * which is particularly useful for implementing recursion in a stack-safe manner.\n *\n * @template T - The type of the final result.\n * @param initial - The initial Trampoline value or thunk to start execution from.\n * @returns The final result of the computation (a non-thunk value).\n */\nexport function trampoline<T>(initial: Trampoline<T>): T {\n let current = initial; // Start with the initial trampoline value\n while (isTrampolineThunk(current)) {\n // Keep unwrapping while we have thunks\n current = current.fn(); // Execute the deferred function to get the next step\n }\n return current; // Once no thunks remain, return the final result\n}\n\n/**\n * Wraps a recursive function inside a trampoline executor.\n *\n * This function transforms a potentially recursive function (that returns a Trampoline<Result>)\n * into a *stack-safe* function that executes iteratively using the `trampoline` runner.\n *\n * In other words, it allows you to write functions that look recursive,\n * but actually run in constant stack space.\n *\n * @template Args - The tuple type representing the argument list of the original function.\n * @template Result - The final return type after all trampoline steps are resolved.\n *\n * @param fn - A function that performs a single step of computation\n * and returns a Trampoline (either a final value or a deferred thunk).\n *\n * @returns A new function with the same arguments, but which automatically\n * runs the trampoline process and returns the *final result* instead\n * of a Trampoline.\n *\n * @example\n * // Example: Computing factorial in a stack-safe way\n * const factorial = makeTrampoline(function fact(n: number, acc: number = 1): Trampoline<number> {\n * return n === 0\n * ? acc\n * : makeTrampolineThunk(() => fact(n - 1, acc * n));\n * });\n *\n * console.log(factorial(100000)); // Works without stack overflow\n */\nexport function makeTrampoline<Args extends any[], Result>(\n fn: (...args: Args) => Trampoline<Result> // A function that returns a trampoline step\n): (...args: Args) => Result {\n // Return a wrapped function that automatically runs the trampoline execution loop\n return (...args: Args) => trampoline(fn(...args));\n}\n\n/**\n * Executes an asynchronous trampoline computation until a final (non-thunk) result is obtained.\n *\n * This function repeatedly invokes asynchronous deferred computations (thunks)\n * in an iterative loop. Each thunk may return either a Trampoline<T> or a Promise<Trampoline<T>>.\n *\n * It ensures that asynchronous recursive functions can run without growing the call stack,\n * making it suitable for stack-safe async recursion.\n *\n * @template T - The type of the final result.\n * @param initial - The initial Trampoline or Promise of Trampoline to start execution from.\n * @returns A Promise that resolves to the final result (a non-thunk value).\n */\nexport async function asyncTrampoline<T>(initial: Trampoline<T> | Promise<Trampoline<T>>): Promise<T> {\n let current = await initial; // Wait for the initial step to resolve if it's a Promise\n\n // Keep executing thunks until we reach a non-thunk (final) value\n while (isTrampolineThunk(current)) {\n current = await current.fn(); // Execute the thunk function (may be async)\n }\n\n // Once the final value is reached, return it\n return current;\n}\n\n/**\n * Wraps an asynchronous recursive function inside an async trampoline executor.\n *\n * This helper transforms a recursive async function that returns a Trampoline<Result>\n * (or Promise<Trampoline<Result>>) into a *stack-safe* async function that executes\n * iteratively via the `asyncTrampoline` runner.\n *\n * @template Args - The tuple type representing the argument list of the original function.\n * @template Result - The final return type after all async trampoline steps are resolved.\n *\n * @param fn - An async or sync function that performs a single step of computation\n * and returns a Trampoline (either a final value or a deferred thunk).\n *\n * @returns An async function with the same arguments, but which automatically\n * runs the trampoline process and resolves to the *final result*.\n *\n * @example\n * // Example: Async factorial using trampoline\n * const asyncFactorial = makeAsyncTrampoline(async function fact(\n * n: number,\n * acc: number = 1\n * ): Promise<Trampoline<number>> {\n * return n === 0\n * ? acc\n * : makeTrampolineThunk(() => fact(n - 1, acc * n));\n * });\n *\n * asyncFactorial(100000).then(console.log); // Works without stack overflow\n */\nexport function makeAsyncTrampoline<Args extends any[], Result>(\n fn: (...args: Args) => Trampoline<Result> | Promise<Trampoline<Result>>\n): (...args: Args) => Promise<Result> {\n // Return a wrapped async function that runs through the async trampoline loop\n return async (...args: Args): Promise<Result> => {\n return asyncTrampoline(fn(...args));\n };\n}\n","import { isComparable } from '../utils';\n\nexport enum DFSOperation {\n VISIT = 0,\n PROCESS = 1\n}\n\nexport class Range<K> {\n constructor(\n public low: K,\n public high: K,\n public includeLow: boolean = true,\n public includeHigh: boolean = true\n ) {\n if (!(isComparable(low) && isComparable(high))) throw new RangeError('low or high is not comparable');\n if (low > high) throw new RangeError('low must be less than or equal to high');\n }\n\n // Determine whether a key is within the range\n isInRange(key: K, comparator: (a: K, b: K) => number): boolean {\n const lowCheck = this.includeLow ? comparator(key, this.low) >= 0 : comparator(key, this.low) > 0;\n const highCheck = this.includeHigh ? comparator(key, this.high) <= 0 : comparator(key, this.high) < 0;\n return lowCheck && highCheck;\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/data-structures/base/iterable-element-base.ts","../../src/data-structures/trie/trie.ts","../../src/utils/utils.ts","../../src/common/index.ts"],"names":["DFSOperation"],"mappings":";;;;;;AAaO,IAAe,sBAAf,MAAgE;AAAA,EAbvE;AAauE,IAAA,MAAA,CAAA,IAAA,EAAA,qBAAA,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAU3D,YAAY,OAAA,EAA4C;AAChE,IAAA,IAAI,OAAA,EAAS;AACX,MAAA,MAAM,EAAE,aAAY,GAAI,OAAA;AACxB,MAAA,IAAI,OAAO,WAAA,KAAgB,UAAA,EAAY,IAAA,CAAK,YAAA,GAAe,WAAA;AAAA,WAAA,IAClD,WAAA,EAAa,MAAM,IAAI,SAAA,CAAU,qCAAqC,CAAA;AAAA,IACjF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQU,YAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASV,IAAI,WAAA,GAAkD;AACpD,IAAA,OAAO,IAAA,CAAK,YAAA;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWA,EAAE,MAAA,CAAO,QAAQ,CAAA,CAAA,GAAK,IAAA,EAAsC;AAC1D,IAAA,OAAO,IAAA,CAAK,YAAA,CAAa,GAAG,IAA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AAA,EAAK,IAAA,CAAK,IAAI,CAAA,IAAK,CAAA,GAAI,UAAA,CAAW,GAAA,EAAK,IAAA,CAAK,IAAI,CAAA,GAAI,CAAA;AACpG,IAAA,OAAO,QAAA,IAAY,SAAA;AAAA,EACrB;AACF","file":"index.cjs","sourcesContent":["import type { ElementCallback, IterableElementBaseOptions, ReduceElementCallback } from '../../types';\n\n/**\n * Base class that makes a data structure iterable and provides common\n * element-wise utilities (e.g., map/filter/reduce/find).\n *\n * @template E The public element type yielded by the structure.\n * @template R The underlying \"raw\" element type used internally or by converters.\n *\n * @remarks\n * This class implements the JavaScript iteration protocol (via `Symbol.iterator`)\n * and offers array-like helpers with predictable time/space complexity.\n */\nexport abstract class IterableElementBase<E, R> implements Iterable<E> {\n /**\n * Create a new iterable base.\n *\n * @param options Optional behavior overrides. When provided, a `toElementFn`\n * is used to convert a raw element (`R`) into a public element (`E`).\n *\n * @remarks\n * Time O(1), Space O(1).\n */\n protected constructor(options?: IterableElementBaseOptions<E, R>) {\n if (options) {\n const { toElementFn } = options;\n if (typeof toElementFn === 'function') this._toElementFn = toElementFn;\n else if (toElementFn) throw new TypeError('toElementFn must be a function type');\n }\n }\n\n /**\n * The converter used to transform a raw element (`R`) into a public element (`E`).\n *\n * @remarks\n * Time O(1), Space O(1).\n */\n protected _toElementFn?: (rawElement: R) => E;\n\n /**\n * Exposes the current `toElementFn`, if configured.\n *\n * @returns The converter function or `undefined` when not set.\n * @remarks\n * Time O(1), Space O(1).\n */\n get toElementFn(): ((rawElement: R) => E) | undefined {\n return this._toElementFn;\n }\n\n /**\n * Returns an iterator over the structure's elements.\n *\n * @param args Optional iterator arguments forwarded to the internal iterator.\n * @returns An `IterableIterator<E>` that yields the elements in traversal order.\n *\n * @remarks\n * Producing the iterator is O(1); consuming the entire iterator is Time O(n) with O(1) extra space.\n */\n *[Symbol.iterator](...args: unknown[]): IterableIterator<E> {\n yield* this._getIterator(...args);\n }\n\n /**\n * Returns an iterator over the values (alias of the default iterator).\n *\n * @returns An `IterableIterator<E>` over all elements.\n * @remarks\n * Creating the iterator is O(1); full iteration is Time O(n), Space O(1).\n */\n *values(): IterableIterator<E> {\n for (const item of this) yield item;\n }\n\n /**\n * Tests whether all elements satisfy the predicate.\n *\n * @template TReturn\n * @param predicate Function invoked for each element with signature `(value, index, self)`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns `true` if every element passes; otherwise `false`.\n *\n * @remarks\n * Time O(n) in the worst case; may exit early when the first failure is found. Space O(1).\n */\n every(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): boolean {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n if (!predicate(item, index++, this)) return false;\n } else {\n const fn = predicate as (this: unknown, v: E, i: number, self: this) => boolean;\n if (!fn.call(thisArg, item, index++, this)) return false;\n }\n }\n return true;\n }\n\n /**\n * Tests whether at least one element satisfies the predicate.\n *\n * @param predicate Function invoked for each element with signature `(value, index, self)`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns `true` if any element passes; otherwise `false`.\n *\n * @remarks\n * Time O(n) in the worst case; may exit early on first success. Space O(1).\n */\n some(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): boolean {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n if (predicate(item, index++, this)) return true;\n } else {\n const fn = predicate as (this: unknown, v: E, i: number, self: this) => boolean;\n if (fn.call(thisArg, item, index++, this)) return true;\n }\n }\n return false;\n }\n\n /**\n * Invokes a callback for each element in iteration order.\n *\n * @param callbackfn Function invoked per element with signature `(value, index, self)`.\n * @param thisArg Optional `this` binding for the callback.\n * @returns `void`.\n *\n * @remarks\n * Time O(n), Space O(1).\n */\n forEach(callbackfn: ElementCallback<E, R, void>, thisArg?: unknown): void {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n callbackfn(item, index++, this);\n } else {\n const fn = callbackfn as (this: unknown, v: E, i: number, self: this) => void;\n fn.call(thisArg, item, index++, this);\n }\n }\n }\n\n /**\n * Finds the first element that satisfies the predicate and returns it.\n *\n * @overload\n * Finds the first element of type `S` (a subtype of `E`) that satisfies the predicate and returns it.\n * @template S\n * @param predicate Type-guard predicate: `(value, index, self) => value is S`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns The matched element typed as `S`, or `undefined` if not found.\n *\n * @overload\n * @param predicate Boolean predicate: `(value, index, self) => boolean`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns The first matching element as `E`, or `undefined` if not found.\n *\n * @remarks\n * Time O(n) in the worst case; may exit early on the first match. Space O(1).\n */\n find<S extends E>(predicate: ElementCallback<E, R, S>, thisArg?: unknown): S | undefined;\n find(predicate: ElementCallback<E, R, unknown>, thisArg?: unknown): E | undefined;\n\n // Implementation signature\n find(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): E | undefined {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n if (predicate(item, index++, this)) return item;\n } else {\n const fn = predicate as (this: unknown, v: E, i: number, self: this) => boolean;\n if (fn.call(thisArg, item, index++, this)) return item;\n }\n }\n return;\n }\n\n /**\n * Checks whether a strictly-equal element exists in the structure.\n *\n * @param element The element to test with `===` equality.\n * @returns `true` if an equal element is found; otherwise `false`.\n *\n * @remarks\n * Time O(n) in the worst case. Space O(1).\n */\n has(element: E): boolean {\n for (const ele of this) if (ele === element) return true;\n return false;\n }\n\n reduce(callbackfn: ReduceElementCallback<E, R>): E;\n reduce(callbackfn: ReduceElementCallback<E, R>, initialValue: E): E;\n reduce<U>(callbackfn: ReduceElementCallback<E, R, U>, initialValue: U): U;\n\n /**\n * Reduces all elements to a single accumulated value.\n *\n * @overload\n * @param callbackfn Reducer of signature `(acc, value, index, self) => nextAcc`. The first element is used as the initial accumulator.\n * @returns The final accumulated value typed as `E`.\n *\n * @overload\n * @param callbackfn Reducer of signature `(acc, value, index, self) => nextAcc`.\n * @param initialValue The initial accumulator value of type `E`.\n * @returns The final accumulated value typed as `E`.\n *\n * @overload\n * @template U The accumulator type when it differs from `E`.\n * @param callbackfn Reducer of signature `(acc: U, value, index, self) => U`.\n * @param initialValue The initial accumulator value of type `U`.\n * @returns The final accumulated value typed as `U`.\n *\n * @remarks\n * Time O(n), Space O(1). Throws if called on an empty structure without `initialValue`.\n */\n reduce<U>(callbackfn: ReduceElementCallback<E, R, U>, initialValue?: U): U {\n let index = 0;\n const iter = this[Symbol.iterator]();\n let acc: U;\n\n if (arguments.length >= 2) {\n acc = initialValue as U;\n } else {\n const first = iter.next();\n if (first.done) throw new TypeError('Reduce of empty structure with no initial value');\n acc = first.value as unknown as U;\n index = 1;\n }\n\n for (const value of iter as unknown as Iterable<E>) {\n acc = callbackfn(acc, value, index++, this);\n }\n return acc;\n }\n\n /**\n * Materializes the elements into a new array.\n *\n * @returns A shallow array copy of the iteration order.\n * @remarks\n * Time O(n), Space O(n).\n */\n toArray(): E[] {\n return [...this];\n }\n\n /**\n * Returns a representation of the structure suitable for quick visualization.\n * Defaults to an array of elements; subclasses may override to provide richer visuals.\n *\n * @returns A visual representation (array by default).\n * @remarks\n * Time O(n), Space O(n).\n */\n toVisual(): E[] {\n return [...this];\n }\n\n /**\n * Prints `toVisual()` to the console. Intended for quick debugging.\n *\n * @returns `void`.\n * @remarks\n * Time O(n) due to materialization, Space O(n) for the intermediate representation.\n */\n print(): void {\n console.log(this.toVisual());\n }\n\n /**\n * Indicates whether the structure currently contains no elements.\n *\n * @returns `true` if empty; otherwise `false`.\n * @remarks\n * Expected Time O(1), Space O(1) for most implementations.\n */\n abstract isEmpty(): boolean;\n\n /**\n * Removes all elements from the structure.\n *\n * @returns `void`.\n * @remarks\n * Expected Time O(1) or O(n) depending on the implementation; Space O(1).\n */\n abstract clear(): void;\n\n /**\n * Creates a structural copy with the same element values and configuration.\n *\n * @returns A clone of the current instance (same concrete type).\n * @remarks\n * Expected Time O(n) to copy elements; Space O(n).\n */\n abstract clone(): this;\n\n /**\n * Maps each element to a new element and returns a new iterable structure.\n *\n * @template EM The mapped element type.\n * @template RM The mapped raw element type used internally by the target structure.\n * @param callback Function with signature `(value, index, self) => mapped`.\n * @param options Optional options for the returned structure, including its `toElementFn`.\n * @param thisArg Optional `this` binding for the callback.\n * @returns A new `IterableElementBase<EM, RM>` containing mapped elements.\n *\n * @remarks\n * Time O(n), Space O(n).\n */\n abstract map<EM, RM>(\n callback: ElementCallback<E, R, EM>,\n options?: IterableElementBaseOptions<EM, RM>,\n thisArg?: unknown\n ): IterableElementBase<EM, RM>;\n\n /**\n * Maps each element to the same element type and returns the same concrete structure type.\n *\n * @param callback Function with signature `(value, index, self) => mappedValue`.\n * @param thisArg Optional `this` binding for the callback.\n * @returns A new instance of the same concrete type with mapped elements.\n *\n * @remarks\n * Time O(n), Space O(n).\n */\n abstract mapSame(callback: ElementCallback<E, R, E>, thisArg?: unknown): this;\n\n /**\n * Filters elements using the provided predicate and returns the same concrete structure type.\n *\n * @param predicate Function with signature `(value, index, self) => boolean`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns A new instance of the same concrete type containing only elements that pass the predicate.\n *\n * @remarks\n * Time O(n), Space O(k) where `k` is the number of kept elements.\n */\n abstract filter(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): this;\n\n /**\n * Internal iterator factory used by the default iterator.\n *\n * @param args Optional iterator arguments.\n * @returns An iterator over elements.\n *\n * @remarks\n * Implementations should yield in O(1) per element with O(1) extra space when possible.\n */\n protected abstract _getIterator(...args: unknown[]): IterableIterator<E>;\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type { ElementCallback, TrieOptions } from '../../types';\nimport { IterableElementBase } from '../base';\n\n/**\n * Node used by Trie to store one character and its children.\n * @remarks Time O(1), Space O(1)\n */\nexport class TrieNode {\n /**\n * Create a Trie node with a character key.\n * @remarks Time O(1), Space O(1)\n * @returns New TrieNode instance.\n */\n\n constructor(key: string) {\n this._key = key;\n this._isEnd = false;\n this._children = new Map<string, TrieNode>();\n }\n\n protected _key: string;\n\n /**\n * Get the character key of this node.\n * @remarks Time O(1), Space O(1)\n * @returns Character key string.\n */\n\n get key(): string {\n return this._key;\n }\n\n /**\n * Set the character key of this node.\n * @remarks Time O(1), Space O(1)\n * @param value - New character key.\n * @returns void\n */\n\n set key(value: string) {\n this._key = value;\n }\n\n protected _children: Map<string, TrieNode>;\n\n /**\n * Get the child map of this node.\n * @remarks Time O(1), Space O(1)\n * @returns Map from character to child node.\n */\n\n get children(): Map<string, TrieNode> {\n return this._children;\n }\n\n /**\n * Replace the child map of this node.\n * @remarks Time O(1), Space O(1)\n * @param value - New map of character → node.\n * @returns void\n */\n\n set children(value: Map<string, TrieNode>) {\n this._children = value;\n }\n\n protected _isEnd: boolean;\n\n /**\n * Check whether this node marks the end of a word.\n * @remarks Time O(1), Space O(1)\n * @returns True if this node ends a word.\n */\n\n get isEnd(): boolean {\n return this._isEnd;\n }\n\n /**\n * Mark this node as the end of a word or not.\n * @remarks Time O(1), Space O(1)\n * @param value - Whether this node ends a word.\n * @returns void\n */\n\n set isEnd(value: boolean) {\n this._isEnd = value;\n }\n}\n\n/**\n * Prefix tree (Trie) for fast prefix queries and word storage.\n * @remarks Time O(1), Space O(1)\n * @template R\n * 1. Node Structure: Each node in a Trie represents a string (or a part of a string). The root node typically represents an empty string.\n * 2. Child Node Relationship: Each node's children represent the strings that can be formed by adding one character to the string at the current node. For example, if a node represents the string 'ca', one of its children might represent 'cat'.\n * 3. Fast Retrieval: Trie allows retrieval in O(m) time complexity, where m is the length of the string to be searched.\n * 4. Space Efficiency: Trie can store a large number of strings very space-efficiently, especially when these strings share common prefixes.\n * 5. Autocomplete and Prediction: Trie can be used for implementing autocomplete and word prediction features, as it can quickly find all strings with a common prefix.\n * 6. Sorting: Trie can be used to sort a set of strings in alphabetical order.\n * 7. String Retrieval: For example, searching for a specific string in a large set of strings.\n * 8. Autocomplete: Providing recommended words or phrases as a user types.\n * 9. Spell Check: Checking the spelling of words.\n * 10. IP Routing: Used in certain types of IP routing algorithms.\n * 11. Text Word Frequency Count: Counting and storing the frequency of words in a large amount of text data.\n * @example\n * // Autocomplete: Prefix validation and checking\n * const autocomplete = new Trie<string>(['gmail.com', 'gmail.co.nz', 'gmail.co.jp', 'yahoo.com', 'outlook.com']);\n *\n * // Get all completions for a prefix\n * const gmailCompletions = autocomplete.getWords('gmail');\n * console.log(gmailCompletions); // ['gmail.com', 'gmail.co.nz', 'gmail.co.jp']\n * @example\n * // File System Path Operations\n * const fileSystem = new Trie<string>([\n * '/home/user/documents/file1.txt',\n * '/home/user/documents/file2.txt',\n * '/home/user/pictures/photo.jpg',\n * '/home/user/pictures/vacation/',\n * '/home/user/downloads'\n * ]);\n *\n * // Find common directory prefix\n * console.log(fileSystem.getLongestCommonPrefix()); // '/home/user/'\n *\n * // List all files in a directory\n * const documentsFiles = fileSystem.getWords('/home/user/documents/');\n * console.log(documentsFiles); // ['/home/user/documents/file1.txt', '/home/user/documents/file2.txt']\n * @example\n * // Autocomplete: Basic word suggestions\n * // Create a trie for autocomplete\n * const autocomplete = new Trie<string>([\n * 'function',\n * 'functional',\n * 'functions',\n * 'class',\n * 'classes',\n * 'classical',\n * 'closure',\n * 'const',\n * 'constructor'\n * ]);\n *\n * // Test autocomplete with different prefixes\n * console.log(autocomplete.getWords('fun')); // ['functional', 'functions', 'function']\n * console.log(autocomplete.getWords('cla')); // ['classes', 'classical', 'class']\n * console.log(autocomplete.getWords('con')); // ['constructor', 'const']\n *\n * // Test with non-matching prefix\n * console.log(autocomplete.getWords('xyz')); // []\n * @example\n * // Dictionary: Case-insensitive word lookup\n * // Create a case-insensitive dictionary\n * const dictionary = new Trie<string>([], { caseSensitive: false });\n *\n * // Add words with mixed casing\n * dictionary.add('Hello');\n * dictionary.add('WORLD');\n * dictionary.add('JavaScript');\n *\n * // Test lookups with different casings\n * console.log(dictionary.has('hello')); // true\n * console.log(dictionary.has('HELLO')); // true\n * console.log(dictionary.has('Hello')); // true\n * console.log(dictionary.has('javascript')); // true\n * console.log(dictionary.has('JAVASCRIPT')); // true\n * @example\n * // IP Address Routing Table\n * // Add IP address prefixes and their corresponding routes\n * const routes = {\n * '192.168.1': 'LAN_SUBNET_1',\n * '192.168.2': 'LAN_SUBNET_2',\n * '10.0.0': 'PRIVATE_NETWORK_1',\n * '10.0.1': 'PRIVATE_NETWORK_2'\n * };\n *\n * const ipRoutingTable = new Trie<string>(Object.keys(routes));\n *\n * // Check IP address prefix matching\n * console.log(ipRoutingTable.hasPrefix('192.168.1')); // true\n * console.log(ipRoutingTable.hasPrefix('192.168.2')); // true\n *\n * // Validate IP address belongs to subnet\n * const ip = '192.168.1.100';\n * const subnet = ip.split('.').slice(0, 3).join('.');\n * console.log(ipRoutingTable.hasPrefix(subnet)); // true\n */\nexport class Trie<R = any> extends IterableElementBase<string, R> {\n /**\n * Create a Trie and optionally bulk-insert words.\n * @remarks Time O(totalChars), Space O(totalChars)\n * @param [words] - Iterable of strings (or raw records if toElementFn is provided).\n * @param [options] - Options such as toElementFn and caseSensitive.\n * @returns New Trie instance.\n */\n\n constructor(words: Iterable<string> | Iterable<R> = [], options?: TrieOptions<R>) {\n super(options);\n if (options) {\n const { caseSensitive } = options;\n if (caseSensitive !== undefined) this._caseSensitive = caseSensitive;\n }\n if (words) {\n this.addMany(words);\n }\n }\n\n protected _size: number = 0;\n\n /**\n * Get the number of stored words.\n * @remarks Time O(1), Space O(1)\n * @returns Word count.\n */\n\n get size(): number {\n return this._size;\n }\n\n protected _caseSensitive: boolean = true;\n\n /**\n * Get whether comparisons are case-sensitive.\n * @remarks Time O(1), Space O(1)\n * @returns True if case-sensitive.\n */\n\n get caseSensitive(): boolean {\n return this._caseSensitive;\n }\n\n protected _root: TrieNode = new TrieNode('');\n\n /**\n * Get the root node.\n * @remarks Time O(1), Space O(1)\n * @returns Root TrieNode.\n */\n\n get root() {\n return this._root;\n }\n\n /**\n * (Protected) Get total count for base class iteration.\n * @remarks Time O(1), Space O(1)\n * @returns Total number of elements.\n */\n\n protected get _total() {\n return this._size;\n }\n\n /**\n * Insert one word into the trie.\n * @remarks Time O(L), Space O(L)\n * @param word - Word to insert.\n * @returns True if the word was newly added.\n */\n\n add(word: string): boolean {\n word = this._caseProcess(word);\n let cur = this.root;\n let isNewWord = false;\n for (const c of word) {\n let nodeC = cur.children.get(c);\n if (!nodeC) {\n nodeC = new TrieNode(c);\n cur.children.set(c, nodeC);\n }\n cur = nodeC;\n }\n if (!cur.isEnd) {\n isNewWord = true;\n cur.isEnd = true;\n this._size++;\n }\n return isNewWord;\n }\n\n /**\n * Insert many words from an iterable.\n * @remarks Time O(ΣL), Space O(ΣL)\n * @param words - Iterable of strings (or raw records if toElementFn is provided).\n * @returns Array of per-word 'added' flags.\n */\n\n addMany(words: Iterable<string> | Iterable<R>): boolean[] {\n const ans: boolean[] = [];\n for (const word of words) {\n if (this.toElementFn) {\n ans.push(this.add(this.toElementFn(word as R)));\n } else {\n ans.push(this.add(word as string));\n }\n }\n return ans;\n }\n\n /**\n * Check whether a word exists.\n * @remarks Time O(L), Space O(1)\n * @param word - Word to search for.\n * @returns True if present.\n */\n\n override has(word: string): boolean {\n word = this._caseProcess(word);\n let cur = this.root;\n for (const c of word) {\n const nodeC = cur.children.get(c);\n if (!nodeC) return false;\n cur = nodeC;\n }\n return cur.isEnd;\n }\n\n /**\n * Check whether the trie is empty.\n * @remarks Time O(1), Space O(1)\n * @returns True if size is 0.\n */\n\n isEmpty(): boolean {\n return this._size === 0;\n }\n\n /**\n * Remove all words and reset to a fresh root.\n * @remarks Time O(1), Space O(1)\n * @returns void\n */\n\n clear(): void {\n this._size = 0;\n this._root = new TrieNode('');\n }\n\n /**\n * Delete one word if present.\n * @remarks Time O(L), Space O(1)\n * @param word - Word to delete.\n * @returns True if a word was removed.\n */\n\n delete(word: string): boolean {\n word = this._caseProcess(word);\n let isDeleted = false;\n const dfs = (cur: TrieNode, i: number): boolean => {\n const char = word[i];\n const child = cur.children.get(char);\n if (child) {\n if (i === word.length - 1) {\n if (child.isEnd) {\n if (child.children.size > 0) {\n child.isEnd = false;\n } else {\n cur.children.delete(char);\n }\n isDeleted = true;\n return true;\n }\n return false;\n }\n const res = dfs(child, i + 1);\n if (res && !cur.isEnd && child.children.size === 0) {\n cur.children.delete(char);\n return true;\n }\n return false;\n }\n return false;\n };\n\n dfs(this.root, 0);\n if (isDeleted) {\n this._size--;\n }\n return isDeleted;\n }\n\n /**\n * Compute the height (max depth) of the trie.\n * @remarks Time O(N), Space O(H)\n * @returns Maximum depth from root to a leaf.\n */\n\n getHeight(): number {\n const startNode = this.root;\n let maxDepth = 0;\n if (startNode) {\n const bfs = (node: TrieNode, level: number) => {\n if (level > maxDepth) {\n maxDepth = level;\n }\n const { children } = node;\n if (children) {\n for (const child of children.entries()) {\n bfs(child[1], level + 1);\n }\n }\n };\n bfs(startNode, 0);\n }\n return maxDepth;\n }\n\n /**\n * Check whether input is a proper prefix of at least one word.\n * @remarks Time O(L), Space O(1)\n * @param input - String to test as prefix.\n * @returns True if input is a prefix but not a full word.\n */\n\n hasPurePrefix(input: string): boolean {\n input = this._caseProcess(input);\n let cur = this.root;\n for (const c of input) {\n const nodeC = cur.children.get(c);\n if (!nodeC) return false;\n cur = nodeC;\n }\n return !cur.isEnd;\n }\n\n /**\n * Check whether any word starts with input.\n * @remarks Time O(L), Space O(1)\n * @param input - String to test as prefix.\n * @returns True if input matches a path from root.\n */\n\n hasPrefix(input: string): boolean {\n input = this._caseProcess(input);\n let cur = this.root;\n for (const c of input) {\n const nodeC = cur.children.get(c);\n if (!nodeC) return false;\n cur = nodeC;\n }\n return true;\n }\n\n /**\n * Check whether the trie’s longest common prefix equals input.\n * @remarks Time O(min(H,L)), Space O(1)\n * @param input - Candidate longest common prefix.\n * @returns True if input equals the common prefix.\n */\n\n hasCommonPrefix(input: string): boolean {\n input = this._caseProcess(input);\n let commonPre = '';\n const dfs = (cur: TrieNode) => {\n commonPre += cur.key;\n if (commonPre === input) return;\n if (cur.isEnd) return;\n if (cur && cur.children && cur.children.size === 1) dfs(Array.from(cur.children.values())[0]);\n else return;\n };\n dfs(this.root);\n return commonPre === input;\n }\n\n /**\n * Return the longest common prefix among all words.\n * @remarks Time O(H), Space O(1)\n * @returns The longest common prefix string.\n */\n\n getLongestCommonPrefix(): string {\n let commonPre = '';\n const dfs = (cur: TrieNode) => {\n commonPre += cur.key;\n if (cur.isEnd) return;\n if (cur && cur.children && cur.children.size === 1) dfs(Array.from(cur.children.values())[0]);\n else return;\n };\n dfs(this.root);\n return commonPre;\n }\n\n /**\n * Collect words under a prefix up to a maximum count.\n * @remarks Time O(K·L), Space O(K·L)\n * @param [prefix] - Prefix to match; default empty string for root.\n * @param [max] - Maximum number of words to return; default is Number.MAX_SAFE_INTEGER.\n * @param [isAllWhenEmptyPrefix] - When true, collect from root even if prefix is empty.\n * @returns Array of collected words (at most max).\n */\n\n getWords(prefix = '', max = Number.MAX_SAFE_INTEGER, isAllWhenEmptyPrefix = false): string[] {\n prefix = this._caseProcess(prefix);\n const words: string[] = [];\n let found = 0;\n\n function dfs(node: TrieNode, word: string) {\n for (const char of node.children.keys()) {\n const charNode = node.children.get(char);\n if (charNode !== undefined) {\n dfs(charNode, word.concat(char));\n }\n }\n if (node.isEnd) {\n if (found > max - 1) return;\n words.push(word);\n found++;\n }\n }\n\n let startNode = this.root;\n\n if (prefix) {\n for (const c of prefix) {\n const nodeC = startNode.children.get(c);\n if (nodeC) {\n startNode = nodeC;\n } else {\n return [];\n }\n }\n }\n\n if (isAllWhenEmptyPrefix || startNode !== this.root) dfs(startNode, prefix);\n\n return words;\n }\n\n /**\n * Deep clone this trie by iterating and inserting all words.\n * @remarks Time O(ΣL), Space O(ΣL)\n * @returns A new trie with the same words and options.\n */\n\n clone(): this {\n const next = this._createInstance();\n for (const x of this) next.add(x);\n return next;\n }\n\n /**\n * Filter words into a new trie of the same class.\n * @remarks Time O(ΣL), Space O(ΣL)\n * @param predicate - Predicate (word, index, trie) → boolean to keep word.\n * @param [thisArg] - Value for `this` inside the predicate.\n * @returns A new trie containing words that satisfy the predicate.\n */\n\n filter(predicate: ElementCallback<string, R, boolean>, thisArg?: any): this {\n const results = this._createInstance();\n let index = 0;\n for (const word of this) {\n if (predicate.call(thisArg, word, index, this)) {\n results.add(word);\n }\n index++;\n }\n return results;\n }\n\n map<RM>(callback: ElementCallback<string, R, string>, options?: TrieOptions<RM>, thisArg?: any): Trie<RM>;\n\n /**\n * Map words into a new trie (possibly different record type).\n * @remarks Time O(ΣL), Space O(ΣL)\n * @template EM\n * @template RM\n * @param callback - Mapping function (word, index, trie) → newWord (string).\n * @param [options] - Options for the output trie (e.g., toElementFn, caseSensitive).\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new Trie constructed from mapped words.\n */\n\n map<EM, RM>(\n callback: ElementCallback<string, R, EM>,\n options?: TrieOptions<RM>,\n thisArg?: any\n ): IterableElementBase<EM, RM>;\n\n map<EM, RM>(callback: ElementCallback<string, R, EM>, options?: TrieOptions<RM>, thisArg?: any): any {\n const newTrie = this._createLike<RM>([], options);\n let i = 0;\n for (const x of this) {\n const v = thisArg === undefined ? callback(x, i++, this) : callback.call(thisArg, x, i++, this);\n if (typeof v !== 'string') {\n throw new TypeError(`Trie.map callback must return string; got ${typeof v}`);\n }\n newTrie.add(v);\n }\n return newTrie;\n }\n\n /**\n * Map words into a new trie of the same element type.\n * @remarks Time O(ΣL), Space O(ΣL)\n * @param callback - Mapping function (word, index, trie) → string.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new trie with mapped words.\n */\n\n mapSame(callback: ElementCallback<string, R, string>, thisArg?: any): this {\n const next = this._createInstance();\n let i = 0;\n for (const key of this) {\n const mapped = thisArg === undefined ? callback(key, i++, this) : callback.call(thisArg, key, i++, this);\n next.add(mapped);\n }\n return next;\n }\n\n /**\n * (Protected) Create an empty instance of the same concrete class.\n * @remarks Time O(1), Space O(1)\n * @param [options] - Options forwarded to the constructor.\n * @returns An empty like-kind trie instance.\n */\n\n protected _createInstance(options?: TrieOptions<R>): this {\n const Ctor: any = this.constructor;\n const next: any = new Ctor([], {\n toElementFn: this.toElementFn,\n caseSensitive: this.caseSensitive,\n ...(options ?? {})\n });\n return next as this;\n }\n\n /**\n * (Protected) Create a like-kind trie and seed it from an iterable.\n * @remarks Time O(ΣL), Space O(ΣL)\n * @template RM\n * @param [elements] - Iterable used to seed the new trie.\n * @param [options] - Options forwarded to the constructor.\n * @returns A like-kind Trie instance.\n */\n\n protected _createLike<RM>(elements: Iterable<string> | Iterable<RM> = [], options?: TrieOptions<RM>): Trie<RM> {\n const Ctor: any = this.constructor;\n return new Ctor(elements, options) as Trie<RM>;\n }\n\n /**\n * (Protected) Spawn an empty like-kind trie instance.\n * @remarks Time O(1), Space O(1)\n * @template RM\n * @param [options] - Options forwarded to the constructor.\n * @returns An empty like-kind Trie instance.\n */\n\n protected _spawnLike<RM>(options?: TrieOptions<RM>): Trie<RM> {\n return this._createLike<RM>([], options);\n }\n\n /**\n * (Protected) Iterate all words in lexicographic order of edges.\n * @remarks Time O(ΣL), Space O(H)\n * @returns Iterator of words.\n */\n\n protected *_getIterator(): IterableIterator<string> {\n function* _dfs(node: TrieNode, path: string): IterableIterator<string> {\n if (node.isEnd) {\n yield path;\n }\n for (const [char, childNode] of node.children) {\n yield* _dfs(childNode, path + char);\n }\n }\n\n yield* _dfs(this.root, '');\n }\n\n /**\n * (Protected) Normalize a string according to case sensitivity.\n * @remarks Time O(L), Space O(L)\n * @param str - Input string to normalize.\n * @returns Normalized string based on caseSensitive.\n */\n\n protected _caseProcess(str: string) {\n if (!this._caseSensitive) {\n str = str.toLowerCase();\n }\n return str;\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\nimport type { Comparable, ComparablePrimitive, Trampoline, TrampolineThunk } from '../types';\n\n/**\n * The function generates a random UUID (Universally Unique Identifier) in TypeScript.\n * @returns A randomly generated UUID (Universally Unique Identifier) in the format\n * 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' where each 'x' is replaced with a random hexadecimal\n * character.\n */\nexport const uuidV4 = function () {\n return 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'.replace(/[x]/g, function (c) {\n const r = (Math.random() * 16) | 0,\n v = c == 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n};\n\n/**\n * The `arrayRemove` function removes elements from an array based on a specified predicate function\n * and returns the removed elements.\n * @param {T[]} array - An array of elements that you want to filter based on the provided predicate\n * function.\n * @param predicate - The `predicate` parameter is a function that takes three arguments:\n * @returns The `arrayRemove` function returns an array containing the elements that satisfy the given\n * `predicate` function.\n */\nexport const arrayRemove = function <T>(array: T[], predicate: (item: T, index: number, array: T[]) => boolean): T[] {\n let i = -1,\n len = array ? array.length : 0;\n const result = [];\n\n while (++i < len) {\n const value = array[i];\n if (predicate(value, i, array)) {\n result.push(value);\n Array.prototype.splice.call(array, i--, 1);\n len--;\n }\n }\n\n return result;\n};\n\n/**\n * The function `getMSB` returns the most significant bit of a given number.\n * @param {number} value - The `value` parameter is a number for which we want to find the position of\n * the Most Significant Bit (MSB). The function `getMSB` takes this number as input and calculates the\n * position of the MSB in its binary representation.\n * @returns The function `getMSB` returns the most significant bit (MSB) of the input `value`. If the\n * input value is less than or equal to 0, it returns 0. Otherwise, it calculates the position of the\n * MSB using the `Math.clz32` function and bitwise left shifts 1 to that position.\n */\nexport const getMSB = (value: number): number => {\n if (value <= 0) {\n return 0;\n }\n return 1 << (31 - Math.clz32(value));\n};\n\n/**\n * The `rangeCheck` function in TypeScript is used to validate if an index is within a specified range\n * and throws a `RangeError` with a custom message if it is out of bounds.\n * @param {number} index - The `index` parameter represents the value that you want to check if it\n * falls within a specified range.\n * @param {number} min - The `min` parameter represents the minimum value that the `index` should be\n * compared against in the `rangeCheck` function.\n * @param {number} max - The `max` parameter in the `rangeCheck` function represents the maximum value\n * that the `index` parameter is allowed to have. If the `index` is greater than this `max` value, a\n * `RangeError` will be thrown.\n * @param [message=Index out of bounds.] - The `message` parameter is a string that represents the\n * error message to be thrown if the index is out of bounds. By default, if no message is provided when\n * calling the `rangeCheck` function, the message \"Index out of bounds.\" will be used.\n */\nexport const rangeCheck = (index: number, min: number, max: number, message = 'Index out of bounds.'): void => {\n if (index < min || index > max) throw new RangeError(message);\n};\n\n/**\n * The function `throwRangeError` throws a RangeError with a custom message if called.\n * @param [message=The value is off-limits.] - The `message` parameter is a string that represents the\n * error message to be displayed when a `RangeError` is thrown. If no message is provided, the default\n * message is 'The value is off-limits.'.\n */\nexport const throwRangeError = (message = 'The value is off-limits.'): void => {\n throw new RangeError(message);\n};\n\n/**\n * The function `isWeakKey` checks if the input is an object or a function in TypeScript.\n * @param {unknown} input - The `input` parameter in the `isWeakKey` function is of type `unknown`,\n * which means it can be any type. The function checks if the `input` is an object (excluding `null`)\n * or a function, and returns a boolean indicating whether the `input` is a weak\n * @returns The function `isWeakKey` returns a boolean value indicating whether the input is an object\n * or a function.\n */\nexport const isWeakKey = (input: unknown): input is object => {\n const inputType = typeof input;\n return (inputType === 'object' && input !== null) || inputType === 'function';\n};\n\n/**\n * The function `calcMinUnitsRequired` calculates the minimum number of units required to accommodate a\n * given total quantity based on a specified unit size.\n * @param {number} totalQuantity - The `totalQuantity` parameter represents the total quantity of items\n * that need to be processed or handled.\n * @param {number} unitSize - The `unitSize` parameter represents the size of each unit or package. It\n * is used in the `calcMinUnitsRequired` function to calculate the minimum number of units required to\n * accommodate a total quantity of items.\n */\nexport const calcMinUnitsRequired = (totalQuantity: number, unitSize: number) =>\n Math.floor((totalQuantity + unitSize - 1) / unitSize);\n\n/**\n * The `roundFixed` function in TypeScript rounds a number to a specified number of decimal places.\n * @param {number} num - The `num` parameter is a number that you want to round to a certain number of\n * decimal places.\n * @param {number} [digit=10] - The `digit` parameter in the `roundFixed` function specifies the number\n * of decimal places to round the number to. By default, it is set to 10 if not provided explicitly.\n * @returns The function `roundFixed` returns a number that is rounded to the specified number of\n * decimal places (default is 10 decimal places).\n */\nexport const roundFixed = (num: number, digit: number = 10) => {\n const multiplier = Math.pow(10, digit);\n return Math.round(num * multiplier) / multiplier;\n};\n\n/**\n * The function `isPrimitiveComparable` checks if a value is a primitive type that can be compared.\n * @param {unknown} value - The `value` parameter in the `isPrimitiveComparable` function is of type\n * `unknown`, which means it can be any type. The function checks if the `value` is a primitive type\n * that can be compared, such as number, bigint, string, or boolean.\n * @returns The function `isPrimitiveComparable` returns a boolean value indicating whether the input\n * `value` is a primitive value that can be compared using standard comparison operators (<, >, <=,\n * >=).\n */\nfunction isPrimitiveComparable(value: unknown): value is ComparablePrimitive {\n const valueType = typeof value;\n if (valueType === 'number') return true;\n // if (valueType === 'number') return !Number.isNaN(value);\n return valueType === 'bigint' || valueType === 'string' || valueType === 'boolean';\n}\n\n/**\n * The function `tryObjectToPrimitive` attempts to convert an object to a comparable primitive value by\n * first checking the `valueOf` method and then the `toString` method.\n * @param {object} obj - The `obj` parameter in the `tryObjectToPrimitive` function is an object that\n * you want to convert to a primitive value. The function attempts to convert the object to a primitive\n * value by first checking if the object has a `valueOf` method. If the `valueOf` method exists, it\n * @returns The function `tryObjectToPrimitive` returns a value of type `ComparablePrimitive` if a\n * primitive comparable value is found within the object, or a string value if the object has a custom\n * `toString` method that does not return `'[object Object]'`. If neither condition is met, the\n * function returns `null`.\n */\nfunction tryObjectToPrimitive(obj: object): ComparablePrimitive | null {\n if (typeof obj.valueOf === 'function') {\n const valueOfResult = obj.valueOf();\n if (valueOfResult !== obj) {\n if (isPrimitiveComparable(valueOfResult)) return valueOfResult;\n if (typeof valueOfResult === 'object' && valueOfResult !== null) return tryObjectToPrimitive(valueOfResult);\n }\n }\n if (typeof obj.toString === 'function') {\n const stringResult = obj.toString();\n if (stringResult !== '[object Object]') return stringResult;\n }\n return null;\n}\n\n/**\n * The function `isComparable` in TypeScript checks if a value is comparable, handling primitive values\n * and objects with optional force comparison.\n * @param {unknown} value - The `value` parameter in the `isComparable` function represents the value\n * that you want to check if it is comparable. It can be of any type (`unknown`), and the function will\n * determine if it is comparable based on certain conditions.\n * @param [isForceObjectComparable=false] - The `isForceObjectComparable` parameter in the\n * `isComparable` function is a boolean flag that determines whether to treat non-primitive values as\n * comparable objects. When set to `true`, it forces the function to consider non-primitive values as\n * comparable objects, regardless of their type.\n * @returns The function `isComparable` returns a boolean value indicating whether the `value` is\n * considered comparable or not.\n */\nexport function isComparable(value: unknown, isForceObjectComparable = false): value is Comparable {\n if (value === null || value === undefined) return false;\n if (isPrimitiveComparable(value)) return true;\n\n if (typeof value !== 'object') return false;\n if (value instanceof Date) return true;\n // if (value instanceof Date) return !Number.isNaN(value.getTime());\n if (isForceObjectComparable) return true;\n const comparableValue = tryObjectToPrimitive(value);\n if (comparableValue === null || comparableValue === undefined) return false;\n return isPrimitiveComparable(comparableValue);\n}\n\n/**\n * Creates a trampoline thunk object.\n *\n * A \"thunk\" is a deferred computation — instead of performing a recursive call immediately,\n * it wraps the next step of the computation in a function. This allows recursive processes\n * to be executed iteratively, preventing stack overflows.\n *\n * @template T - The type of the final computation result.\n * @param computation - A function that, when executed, returns the next trampoline step.\n * @returns A TrampolineThunk object containing the deferred computation.\n */\nexport const makeTrampolineThunk = <T>(computation: () => Trampoline<T>): TrampolineThunk<T> => ({\n isThunk: true, // Marker indicating this is a thunk\n fn: computation // The deferred computation function\n});\n\n/**\n * Type guard to check whether a given value is a TrampolineThunk.\n *\n * This function is used to distinguish between a final computation result (value)\n * and a deferred computation (thunk).\n *\n * @template T - The type of the value being checked.\n * @param value - The value to test.\n * @returns True if the value is a valid TrampolineThunk, false otherwise.\n */\nexport const isTrampolineThunk = <T>(value: Trampoline<T>): value is TrampolineThunk<T> =>\n typeof value === 'object' && // Must be an object\n value !== null && // Must not be null\n 'isThunk' in value && // Must have the 'isThunk' property\n value.isThunk; // The flag must be true\n\n/**\n * Executes a trampoline computation until a final (non-thunk) result is obtained.\n *\n * The trampoline function repeatedly invokes the deferred computations (thunks)\n * in an iterative loop. This avoids deep recursive calls and prevents stack overflow,\n * which is particularly useful for implementing recursion in a stack-safe manner.\n *\n * @template T - The type of the final result.\n * @param initial - The initial Trampoline value or thunk to start execution from.\n * @returns The final result of the computation (a non-thunk value).\n */\nexport function trampoline<T>(initial: Trampoline<T>): T {\n let current = initial; // Start with the initial trampoline value\n while (isTrampolineThunk(current)) {\n // Keep unwrapping while we have thunks\n current = current.fn(); // Execute the deferred function to get the next step\n }\n return current; // Once no thunks remain, return the final result\n}\n\n/**\n * Wraps a recursive function inside a trampoline executor.\n *\n * This function transforms a potentially recursive function (that returns a Trampoline<Result>)\n * into a *stack-safe* function that executes iteratively using the `trampoline` runner.\n *\n * In other words, it allows you to write functions that look recursive,\n * but actually run in constant stack space.\n *\n * @template Args - The tuple type representing the argument list of the original function.\n * @template Result - The final return type after all trampoline steps are resolved.\n *\n * @param fn - A function that performs a single step of computation\n * and returns a Trampoline (either a final value or a deferred thunk).\n *\n * @returns A new function with the same arguments, but which automatically\n * runs the trampoline process and returns the *final result* instead\n * of a Trampoline.\n *\n * @example\n * // Example: Computing factorial in a stack-safe way\n * const factorial = makeTrampoline(function fact(n: number, acc: number = 1): Trampoline<number> {\n * return n === 0\n * ? acc\n * : makeTrampolineThunk(() => fact(n - 1, acc * n));\n * });\n *\n * console.log(factorial(100000)); // Works without stack overflow\n */\nexport function makeTrampoline<Args extends any[], Result>(\n fn: (...args: Args) => Trampoline<Result> // A function that returns a trampoline step\n): (...args: Args) => Result {\n // Return a wrapped function that automatically runs the trampoline execution loop\n return (...args: Args) => trampoline(fn(...args));\n}\n\n/**\n * Executes an asynchronous trampoline computation until a final (non-thunk) result is obtained.\n *\n * This function repeatedly invokes asynchronous deferred computations (thunks)\n * in an iterative loop. Each thunk may return either a Trampoline<T> or a Promise<Trampoline<T>>.\n *\n * It ensures that asynchronous recursive functions can run without growing the call stack,\n * making it suitable for stack-safe async recursion.\n *\n * @template T - The type of the final result.\n * @param initial - The initial Trampoline or Promise of Trampoline to start execution from.\n * @returns A Promise that resolves to the final result (a non-thunk value).\n */\nexport async function asyncTrampoline<T>(initial: Trampoline<T> | Promise<Trampoline<T>>): Promise<T> {\n let current = await initial; // Wait for the initial step to resolve if it's a Promise\n\n // Keep executing thunks until we reach a non-thunk (final) value\n while (isTrampolineThunk(current)) {\n current = await current.fn(); // Execute the thunk function (may be async)\n }\n\n // Once the final value is reached, return it\n return current;\n}\n\n/**\n * Wraps an asynchronous recursive function inside an async trampoline executor.\n *\n * This helper transforms a recursive async function that returns a Trampoline<Result>\n * (or Promise<Trampoline<Result>>) into a *stack-safe* async function that executes\n * iteratively via the `asyncTrampoline` runner.\n *\n * @template Args - The tuple type representing the argument list of the original function.\n * @template Result - The final return type after all async trampoline steps are resolved.\n *\n * @param fn - An async or sync function that performs a single step of computation\n * and returns a Trampoline (either a final value or a deferred thunk).\n *\n * @returns An async function with the same arguments, but which automatically\n * runs the trampoline process and resolves to the *final result*.\n *\n * @example\n * // Example: Async factorial using trampoline\n * const asyncFactorial = makeAsyncTrampoline(async function fact(\n * n: number,\n * acc: number = 1\n * ): Promise<Trampoline<number>> {\n * return n === 0\n * ? acc\n * : makeTrampolineThunk(() => fact(n - 1, acc * n));\n * });\n *\n * asyncFactorial(100000).then(console.log); // Works without stack overflow\n */\nexport function makeAsyncTrampoline<Args extends any[], Result>(\n fn: (...args: Args) => Trampoline<Result> | Promise<Trampoline<Result>>\n): (...args: Args) => Promise<Result> {\n // Return a wrapped async function that runs through the async trampoline loop\n return async (...args: Args): Promise<Result> => {\n return asyncTrampoline(fn(...args));\n };\n}\n","import { isComparable } from '../utils';\n\nexport enum DFSOperation {\n VISIT = 0,\n PROCESS = 1\n}\n\nexport class Range<K> {\n constructor(\n public low: K,\n public high: K,\n public includeLow: boolean = true,\n public includeHigh: boolean = true\n ) {\n if (!(isComparable(low) && isComparable(high))) throw new RangeError('low or high is not comparable');\n if (low > high) throw new RangeError('low must be less than or equal to high');\n }\n\n // Determine whether a key is within the range\n isInRange(key: K, comparator: (a: K, b: K) => number): boolean {\n const lowCheck = this.includeLow ? comparator(key, this.low) >= 0 : comparator(key, this.low) > 0;\n const highCheck = this.includeHigh ? comparator(key, this.high) <= 0 : comparator(key, this.high) < 0;\n return lowCheck && highCheck;\n }\n}\n"]}