stack-typed 2.1.1 → 2.1.2
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.
- package/dist/cjs/index.cjs +552 -0
- package/dist/cjs/index.cjs.map +1 -0
- package/dist/esm/index.mjs +548 -0
- package/dist/esm/index.mjs.map +1 -0
- package/dist/types/data-structures/base/index.d.ts +2 -1
- package/dist/types/data-structures/binary-tree/avl-tree-counter.d.ts +182 -2
- package/dist/types/data-structures/binary-tree/avl-tree-multi-map.d.ts +135 -2
- package/dist/types/data-structures/binary-tree/avl-tree.d.ts +291 -2
- package/dist/types/data-structures/binary-tree/binary-indexed-tree.d.ts +174 -1
- package/dist/types/data-structures/binary-tree/binary-tree.d.ts +754 -29
- package/dist/types/data-structures/binary-tree/bst.d.ts +413 -12
- package/dist/types/data-structures/binary-tree/index.d.ts +3 -2
- package/dist/types/data-structures/binary-tree/red-black-tree.d.ts +208 -3
- package/dist/types/data-structures/binary-tree/segment-tree.d.ts +160 -1
- package/dist/types/data-structures/binary-tree/tree-counter.d.ts +190 -2
- package/dist/types/data-structures/binary-tree/tree-multi-map.d.ts +270 -2
- package/dist/types/data-structures/graph/abstract-graph.d.ts +340 -14
- package/dist/types/data-structures/graph/directed-graph.d.ts +207 -1
- package/dist/types/data-structures/graph/index.d.ts +2 -1
- package/dist/types/data-structures/graph/map-graph.d.ts +78 -1
- package/dist/types/data-structures/graph/undirected-graph.d.ts +188 -1
- package/dist/types/data-structures/hash/hash-map.d.ts +345 -19
- package/dist/types/data-structures/hash/index.d.ts +0 -1
- package/dist/types/data-structures/heap/heap.d.ts +503 -5
- package/dist/types/data-structures/heap/index.d.ts +2 -0
- package/dist/types/data-structures/heap/max-heap.d.ts +32 -1
- package/dist/types/data-structures/heap/min-heap.d.ts +33 -1
- package/dist/types/data-structures/index.d.ts +7 -7
- package/dist/types/data-structures/linked-list/doubly-linked-list.d.ts +769 -2
- package/dist/types/data-structures/linked-list/singly-linked-list.d.ts +451 -2
- package/dist/types/data-structures/linked-list/skip-linked-list.d.ts +27 -4
- package/dist/types/data-structures/matrix/index.d.ts +1 -1
- package/dist/types/data-structures/matrix/matrix.d.ts +168 -7
- package/dist/types/data-structures/matrix/navigator.d.ts +54 -13
- package/dist/types/data-structures/priority-queue/max-priority-queue.d.ts +27 -1
- package/dist/types/data-structures/priority-queue/min-priority-queue.d.ts +26 -1
- package/dist/types/data-structures/priority-queue/priority-queue.d.ts +15 -2
- package/dist/types/data-structures/queue/deque.d.ts +431 -4
- package/dist/types/data-structures/queue/queue.d.ts +308 -4
- package/dist/types/data-structures/stack/stack.d.ts +306 -2
- package/dist/types/data-structures/tree/tree.d.ts +62 -1
- package/dist/types/data-structures/trie/trie.d.ts +350 -4
- package/dist/types/index.d.ts +11 -2
- package/dist/{interfaces → types/interfaces}/binary-tree.d.ts +1 -1
- package/dist/types/types/data-structures/base/index.d.ts +1 -0
- package/dist/types/types/data-structures/binary-tree/avl-tree-counter.d.ts +2 -0
- package/dist/types/types/data-structures/binary-tree/avl-tree-multi-map.d.ts +2 -0
- package/dist/types/types/data-structures/binary-tree/avl-tree.d.ts +2 -0
- package/dist/types/types/data-structures/binary-tree/binary-indexed-tree.d.ts +1 -0
- package/dist/types/types/data-structures/binary-tree/binary-tree.d.ts +29 -0
- package/dist/types/types/data-structures/binary-tree/bst.d.ts +12 -0
- package/dist/{data-structures → types/types/data-structures}/binary-tree/index.d.ts +2 -3
- package/dist/types/types/data-structures/binary-tree/red-black-tree.d.ts +3 -0
- package/dist/types/types/data-structures/binary-tree/segment-tree.d.ts +1 -0
- package/dist/types/types/data-structures/binary-tree/tree-counter.d.ts +2 -0
- package/dist/types/types/data-structures/binary-tree/tree-multi-map.d.ts +2 -0
- package/dist/types/types/data-structures/graph/abstract-graph.d.ts +14 -0
- package/dist/types/types/data-structures/graph/directed-graph.d.ts +1 -0
- package/dist/{data-structures → types/types/data-structures}/graph/index.d.ts +1 -2
- package/dist/types/types/data-structures/graph/map-graph.d.ts +1 -0
- package/dist/types/types/data-structures/graph/undirected-graph.d.ts +1 -0
- package/dist/types/types/data-structures/hash/hash-map.d.ts +19 -0
- package/dist/types/types/data-structures/hash/index.d.ts +2 -0
- package/dist/types/types/data-structures/heap/heap.d.ts +5 -0
- package/dist/types/types/data-structures/heap/index.d.ts +1 -0
- package/dist/types/types/data-structures/heap/max-heap.d.ts +1 -0
- package/dist/types/types/data-structures/heap/min-heap.d.ts +1 -0
- package/dist/types/types/data-structures/linked-list/doubly-linked-list.d.ts +2 -0
- package/dist/types/types/data-structures/linked-list/singly-linked-list.d.ts +2 -0
- package/dist/types/types/data-structures/linked-list/skip-linked-list.d.ts +4 -0
- package/dist/types/types/data-structures/matrix/matrix.d.ts +7 -0
- package/dist/types/types/data-structures/matrix/navigator.d.ts +14 -0
- package/dist/types/types/data-structures/priority-queue/max-priority-queue.d.ts +1 -0
- package/dist/types/types/data-structures/priority-queue/min-priority-queue.d.ts +1 -0
- package/dist/types/types/data-structures/priority-queue/priority-queue.d.ts +2 -0
- package/dist/types/types/data-structures/queue/deque.d.ts +4 -0
- package/dist/types/types/data-structures/queue/queue.d.ts +4 -0
- package/dist/types/types/data-structures/stack/stack.d.ts +2 -0
- package/dist/types/types/data-structures/tree/tree.d.ts +1 -0
- package/dist/types/types/data-structures/trie/trie.d.ts +4 -0
- package/dist/types/types/index.d.ts +3 -0
- package/dist/types/types/utils/index.d.ts +2 -0
- package/dist/types/types/utils/utils.d.ts +22 -0
- package/dist/types/utils/index.d.ts +1 -1
- package/dist/types/utils/utils.d.ts +209 -22
- package/dist/umd/stack-typed.js +563 -0
- package/dist/umd/stack-typed.js.map +1 -0
- package/dist/umd/stack-typed.min.js +9 -0
- package/dist/umd/stack-typed.min.js.map +1 -0
- package/package.json +25 -5
- package/src/data-structures/binary-tree/avl-tree-counter.ts +4 -4
- package/src/data-structures/binary-tree/avl-tree-multi-map.ts +1 -1
- package/src/data-structures/binary-tree/avl-tree.ts +2 -2
- package/src/data-structures/binary-tree/binary-tree.ts +4 -4
- package/src/data-structures/binary-tree/bst.ts +1 -1
- package/src/data-structures/binary-tree/red-black-tree.ts +2 -2
- package/src/data-structures/binary-tree/tree-counter.ts +4 -4
- package/src/data-structures/binary-tree/tree-multi-map.ts +1 -1
- package/src/data-structures/heap/heap.ts +5 -5
- package/src/data-structures/linked-list/singly-linked-list.ts +2 -2
- package/src/interfaces/binary-tree.ts +1 -1
- package/tsconfig.base.json +23 -0
- package/tsconfig.json +8 -34
- package/tsconfig.test.json +8 -0
- package/tsconfig.types.json +15 -0
- package/tsup.config.js +28 -0
- package/tsup.node.config.js +37 -0
- package/dist/common/index.js +0 -28
- package/dist/constants/index.js +0 -8
- package/dist/data-structures/base/index.d.ts +0 -2
- package/dist/data-structures/base/index.js +0 -18
- package/dist/data-structures/base/iterable-element-base.js +0 -243
- package/dist/data-structures/base/iterable-entry-base.js +0 -183
- package/dist/data-structures/base/linear-base.js +0 -415
- package/dist/data-structures/binary-tree/avl-tree-counter.d.ts +0 -182
- package/dist/data-structures/binary-tree/avl-tree-counter.js +0 -374
- package/dist/data-structures/binary-tree/avl-tree-multi-map.d.ts +0 -135
- package/dist/data-structures/binary-tree/avl-tree-multi-map.js +0 -250
- package/dist/data-structures/binary-tree/avl-tree.d.ts +0 -291
- package/dist/data-structures/binary-tree/avl-tree.js +0 -611
- package/dist/data-structures/binary-tree/binary-indexed-tree.d.ts +0 -174
- package/dist/data-structures/binary-tree/binary-indexed-tree.js +0 -294
- package/dist/data-structures/binary-tree/binary-tree.d.ts +0 -754
- package/dist/data-structures/binary-tree/binary-tree.js +0 -1925
- package/dist/data-structures/binary-tree/bst.d.ts +0 -413
- package/dist/data-structures/binary-tree/bst.js +0 -903
- package/dist/data-structures/binary-tree/index.js +0 -26
- package/dist/data-structures/binary-tree/red-black-tree.d.ts +0 -208
- package/dist/data-structures/binary-tree/red-black-tree.js +0 -546
- package/dist/data-structures/binary-tree/segment-tree.d.ts +0 -160
- package/dist/data-structures/binary-tree/segment-tree.js +0 -297
- package/dist/data-structures/binary-tree/tree-counter.d.ts +0 -190
- package/dist/data-structures/binary-tree/tree-counter.js +0 -413
- package/dist/data-structures/binary-tree/tree-multi-map.d.ts +0 -270
- package/dist/data-structures/binary-tree/tree-multi-map.js +0 -384
- package/dist/data-structures/graph/abstract-graph.d.ts +0 -340
- package/dist/data-structures/graph/abstract-graph.js +0 -896
- package/dist/data-structures/graph/directed-graph.d.ts +0 -207
- package/dist/data-structures/graph/directed-graph.js +0 -525
- package/dist/data-structures/graph/index.js +0 -20
- package/dist/data-structures/graph/map-graph.d.ts +0 -78
- package/dist/data-structures/graph/map-graph.js +0 -107
- package/dist/data-structures/graph/undirected-graph.d.ts +0 -188
- package/dist/data-structures/graph/undirected-graph.js +0 -424
- package/dist/data-structures/hash/hash-map.d.ts +0 -345
- package/dist/data-structures/hash/hash-map.js +0 -692
- package/dist/data-structures/hash/index.d.ts +0 -1
- package/dist/data-structures/hash/index.js +0 -17
- package/dist/data-structures/heap/heap.d.ts +0 -503
- package/dist/data-structures/heap/heap.js +0 -901
- package/dist/data-structures/heap/index.d.ts +0 -3
- package/dist/data-structures/heap/index.js +0 -19
- package/dist/data-structures/heap/max-heap.d.ts +0 -32
- package/dist/data-structures/heap/max-heap.js +0 -40
- package/dist/data-structures/heap/min-heap.d.ts +0 -33
- package/dist/data-structures/heap/min-heap.js +0 -31
- package/dist/data-structures/index.js +0 -28
- package/dist/data-structures/linked-list/doubly-linked-list.d.ts +0 -769
- package/dist/data-structures/linked-list/doubly-linked-list.js +0 -1111
- package/dist/data-structures/linked-list/index.js +0 -19
- package/dist/data-structures/linked-list/singly-linked-list.d.ts +0 -451
- package/dist/data-structures/linked-list/singly-linked-list.js +0 -850
- package/dist/data-structures/linked-list/skip-linked-list.d.ts +0 -27
- package/dist/data-structures/linked-list/skip-linked-list.js +0 -144
- package/dist/data-structures/matrix/index.js +0 -18
- package/dist/data-structures/matrix/matrix.d.ts +0 -168
- package/dist/data-structures/matrix/matrix.js +0 -448
- package/dist/data-structures/matrix/navigator.d.ts +0 -55
- package/dist/data-structures/matrix/navigator.js +0 -111
- package/dist/data-structures/priority-queue/index.js +0 -19
- package/dist/data-structures/priority-queue/max-priority-queue.d.ts +0 -27
- package/dist/data-structures/priority-queue/max-priority-queue.js +0 -34
- package/dist/data-structures/priority-queue/min-priority-queue.d.ts +0 -26
- package/dist/data-structures/priority-queue/min-priority-queue.js +0 -24
- package/dist/data-structures/priority-queue/priority-queue.d.ts +0 -15
- package/dist/data-structures/priority-queue/priority-queue.js +0 -20
- package/dist/data-structures/queue/deque.d.ts +0 -431
- package/dist/data-structures/queue/deque.js +0 -879
- package/dist/data-structures/queue/index.js +0 -18
- package/dist/data-structures/queue/queue.d.ts +0 -308
- package/dist/data-structures/queue/queue.js +0 -473
- package/dist/data-structures/stack/index.js +0 -17
- package/dist/data-structures/stack/stack.d.ts +0 -306
- package/dist/data-structures/stack/stack.js +0 -401
- package/dist/data-structures/tree/index.js +0 -17
- package/dist/data-structures/tree/tree.d.ts +0 -62
- package/dist/data-structures/tree/tree.js +0 -107
- package/dist/data-structures/trie/index.js +0 -17
- package/dist/data-structures/trie/trie.d.ts +0 -350
- package/dist/data-structures/trie/trie.js +0 -610
- package/dist/index.d.ts +0 -12
- package/dist/index.js +0 -28
- package/dist/interfaces/binary-tree.js +0 -2
- package/dist/interfaces/doubly-linked-list.js +0 -2
- package/dist/interfaces/graph.js +0 -2
- package/dist/interfaces/heap.js +0 -2
- package/dist/interfaces/index.js +0 -24
- package/dist/interfaces/navigator.js +0 -2
- package/dist/interfaces/priority-queue.js +0 -2
- package/dist/interfaces/segment-tree.js +0 -2
- package/dist/interfaces/singly-linked-list.js +0 -2
- package/dist/types/common.js +0 -2
- package/dist/types/data-structures/base/base.js +0 -2
- package/dist/types/data-structures/base/index.js +0 -17
- package/dist/types/data-structures/binary-tree/avl-tree-counter.js +0 -2
- package/dist/types/data-structures/binary-tree/avl-tree-multi-map.js +0 -2
- package/dist/types/data-structures/binary-tree/avl-tree.js +0 -2
- package/dist/types/data-structures/binary-tree/binary-indexed-tree.js +0 -2
- package/dist/types/data-structures/binary-tree/binary-tree.js +0 -2
- package/dist/types/data-structures/binary-tree/bst.js +0 -2
- package/dist/types/data-structures/binary-tree/index.js +0 -25
- package/dist/types/data-structures/binary-tree/red-black-tree.js +0 -2
- package/dist/types/data-structures/binary-tree/segment-tree.js +0 -2
- package/dist/types/data-structures/binary-tree/tree-counter.js +0 -2
- package/dist/types/data-structures/binary-tree/tree-multi-map.js +0 -2
- package/dist/types/data-structures/graph/abstract-graph.js +0 -2
- package/dist/types/data-structures/graph/directed-graph.js +0 -2
- package/dist/types/data-structures/graph/index.js +0 -19
- package/dist/types/data-structures/graph/map-graph.js +0 -2
- package/dist/types/data-structures/graph/undirected-graph.js +0 -2
- package/dist/types/data-structures/hash/hash-map.js +0 -2
- package/dist/types/data-structures/hash/index.js +0 -17
- package/dist/types/data-structures/heap/heap.js +0 -2
- package/dist/types/data-structures/heap/index.js +0 -17
- package/dist/types/data-structures/heap/max-heap.js +0 -2
- package/dist/types/data-structures/heap/min-heap.js +0 -2
- package/dist/types/data-structures/index.js +0 -28
- package/dist/types/data-structures/linked-list/doubly-linked-list.js +0 -2
- package/dist/types/data-structures/linked-list/index.js +0 -19
- package/dist/types/data-structures/linked-list/singly-linked-list.js +0 -2
- package/dist/types/data-structures/linked-list/skip-linked-list.js +0 -2
- package/dist/types/data-structures/matrix/index.js +0 -18
- package/dist/types/data-structures/matrix/matrix.js +0 -2
- package/dist/types/data-structures/matrix/navigator.js +0 -2
- package/dist/types/data-structures/priority-queue/index.js +0 -19
- package/dist/types/data-structures/priority-queue/max-priority-queue.js +0 -2
- package/dist/types/data-structures/priority-queue/min-priority-queue.js +0 -2
- package/dist/types/data-structures/priority-queue/priority-queue.js +0 -2
- package/dist/types/data-structures/queue/deque.js +0 -2
- package/dist/types/data-structures/queue/index.js +0 -18
- package/dist/types/data-structures/queue/queue.js +0 -2
- package/dist/types/data-structures/stack/index.js +0 -17
- package/dist/types/data-structures/stack/stack.js +0 -2
- package/dist/types/data-structures/tree/index.js +0 -17
- package/dist/types/data-structures/tree/tree.js +0 -2
- package/dist/types/data-structures/trie/index.js +0 -17
- package/dist/types/data-structures/trie/trie.js +0 -2
- package/dist/types/index.js +0 -19
- package/dist/types/utils/index.js +0 -18
- package/dist/types/utils/utils.js +0 -2
- package/dist/types/utils/validate-type.js +0 -2
- package/dist/utils/index.d.ts +0 -2
- package/dist/utils/index.js +0 -18
- package/dist/utils/number.js +0 -24
- package/dist/utils/utils.d.ts +0 -209
- package/dist/utils/utils.js +0 -353
- package/dist/{common → types/common}/index.d.ts +0 -0
- package/dist/{constants → types/constants}/index.d.ts +0 -0
- package/dist/{data-structures → types/data-structures}/base/iterable-element-base.d.ts +0 -0
- package/dist/{data-structures → types/data-structures}/base/iterable-entry-base.d.ts +0 -0
- package/dist/{data-structures → types/data-structures}/base/linear-base.d.ts +0 -0
- package/dist/{interfaces → types/interfaces}/doubly-linked-list.d.ts +0 -0
- package/dist/{interfaces → types/interfaces}/graph.d.ts +0 -0
- package/dist/{interfaces → types/interfaces}/heap.d.ts +0 -0
- package/dist/{interfaces → types/interfaces}/index.d.ts +0 -0
- package/dist/{interfaces → types/interfaces}/navigator.d.ts +0 -0
- package/dist/{interfaces → types/interfaces}/priority-queue.d.ts +0 -0
- package/dist/{interfaces → types/interfaces}/segment-tree.d.ts +0 -0
- package/dist/{interfaces → types/interfaces}/singly-linked-list.d.ts +0 -0
- package/dist/types/{common.d.ts → types/common.d.ts} +0 -0
- package/dist/types/{data-structures → types/data-structures}/base/base.d.ts +0 -0
- package/dist/{data-structures → types/types/data-structures}/index.d.ts +7 -7
- package/dist/{data-structures → types/types/data-structures}/linked-list/index.d.ts +0 -0
- package/dist/{data-structures → types/types/data-structures}/matrix/index.d.ts +1 -1
- /package/dist/{data-structures → types/types/data-structures}/priority-queue/index.d.ts +0 -0
- /package/dist/{data-structures → types/types/data-structures}/queue/index.d.ts +0 -0
- /package/dist/{data-structures → types/types/data-structures}/stack/index.d.ts +0 -0
- /package/dist/{data-structures → types/types/data-structures}/tree/index.d.ts +0 -0
- /package/dist/{data-structures → types/types/data-structures}/trie/index.d.ts +0 -0
- /package/dist/types/{utils → types/utils}/validate-type.d.ts +0 -0
- /package/dist/{utils → types/utils}/number.d.ts +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/index.ts","../../src/data-structures/base/iterable-element-base.ts","../../src/data-structures/stack/stack.ts","../../src/utils/utils.ts","../../src/common/index.ts"],"sourcesContent":["/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\nexport * from './data-structures/stack';\nexport * from './types/data-structures/stack';\nexport * from './types/common';\nexport * from './types/utils';\nexport * from './common';","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, IterableElementBaseOptions, StackOptions } from '../../types';\nimport { IterableElementBase } from '../base';\n\n/**\n * LIFO stack with array storage and optional record→element conversion.\n * @remarks Time O(1), Space O(1)\n * @template E\n * @template R\n * 1. Last In, First Out (LIFO): The core characteristic of a stack is its last in, first out nature, meaning the last element added to the stack will be the first to be removed.\n * 2. Uses: Stacks are commonly used for managing a series of tasks or elements that need to be processed in a last in, first out manner. They are widely used in various scenarios, such as in function calls in programming languages, evaluation of arithmetic expressions, and backtracking algorithms.\n * 3. Performance: Stack operations are typically O(1) in time complexity, meaning that regardless of the stack's size, adding, removing, and viewing the top element are very fast operations.\n * 4. Function Calls: In most modern programming languages, the records of function calls are managed through a stack. When a function is called, its record (including parameters, local variables, and return address) is 'pushed' into the stack. When the function returns, its record is 'popped' from the stack.\n * 5. Expression Evaluation: Used for the evaluation of arithmetic or logical expressions, especially when dealing with parenthesis matching and operator precedence.\n * 6. Backtracking Algorithms: In problems where multiple branches need to be explored but only one branch can be explored at a time, stacks can be used to save the state at each branching point.\n * @example\n * // Balanced Parentheses or Brackets\n * type ValidCharacters = ')' | '(' | ']' | '[' | '}' | '{';\n *\n * const stack = new Stack<string>();\n * const input: ValidCharacters[] = '[({})]'.split('') as ValidCharacters[];\n * const matches: { [key in ValidCharacters]?: ValidCharacters } = { ')': '(', ']': '[', '}': '{' };\n * for (const char of input) {\n * if ('([{'.includes(char)) {\n * stack.push(char);\n * } else if (')]}'.includes(char)) {\n * if (stack.pop() !== matches[char]) {\n * fail('Parentheses are not balanced');\n * }\n * }\n * }\n * console.log(stack.isEmpty()); // true\n * @example\n * // Expression Evaluation and Conversion\n * const stack = new Stack<number>();\n * const expression = [5, 3, '+']; // Equivalent to 5 + 3\n * expression.forEach(token => {\n * if (typeof token === 'number') {\n * stack.push(token);\n * } else {\n * const b = stack.pop()!;\n * const a = stack.pop()!;\n * stack.push(token === '+' ? a + b : 0); // Only handling '+' here\n * }\n * });\n * console.log(stack.pop()); // 8\n * @example\n * // Depth-First Search (DFS)\n * const stack = new Stack<number>();\n * const graph: { [key in number]: number[] } = { 1: [2, 3], 2: [4], 3: [5], 4: [], 5: [] };\n * const visited: number[] = [];\n * stack.push(1);\n * while (!stack.isEmpty()) {\n * const node = stack.pop()!;\n * if (!visited.includes(node)) {\n * visited.push(node);\n * graph[node].forEach(neighbor => stack.push(neighbor));\n * }\n * }\n * console.log(visited); // [1, 3, 5, 2, 4]\n * @example\n * // Backtracking Algorithms\n * const stack = new Stack<[number, number]>();\n * const maze = [\n * ['S', ' ', 'X'],\n * ['X', ' ', 'X'],\n * [' ', ' ', 'E']\n * ];\n * const start: [number, number] = [0, 0];\n * const end = [2, 2];\n * const directions = [\n * [0, 1], // To the right\n * [1, 0], // down\n * [0, -1], // left\n * [-1, 0] // up\n * ];\n *\n * const visited = new Set<string>(); // Used to record visited nodes\n * stack.push(start);\n * const path: number[][] = [];\n *\n * while (!stack.isEmpty()) {\n * const [x, y] = stack.pop()!;\n * if (visited.has(`${x},${y}`)) continue; // Skip already visited nodes\n * visited.add(`${x},${y}`);\n *\n * path.push([x, y]);\n *\n * if (x === end[0] && y === end[1]) {\n * break; // Find the end point and exit\n * }\n *\n * for (const [dx, dy] of directions) {\n * const nx = x + dx;\n * const ny = y + dy;\n * if (\n * maze[nx]?.[ny] === ' ' || // feasible path\n * maze[nx]?.[ny] === 'E' // destination\n * ) {\n * stack.push([nx, ny]);\n * }\n * }\n * }\n *\n * expect(path).toContainEqual(end);\n * @example\n * // Function Call Stack\n * const functionStack = new Stack<string>();\n * functionStack.push('main');\n * functionStack.push('foo');\n * functionStack.push('bar');\n * console.log(functionStack.pop()); // 'bar'\n * console.log(functionStack.pop()); // 'foo'\n * console.log(functionStack.pop()); // 'main'\n * @example\n * // Simplify File Paths\n * const stack = new Stack<string>();\n * const path = '/a/./b/../../c';\n * path.split('/').forEach(segment => {\n * if (segment === '..') stack.pop();\n * else if (segment && segment !== '.') stack.push(segment);\n * });\n * console.log(stack.elements.join('/')); // 'c'\n * @example\n * // Stock Span Problem\n * const stack = new Stack<number>();\n * const prices = [100, 80, 60, 70, 60, 75, 85];\n * const spans: number[] = [];\n * prices.forEach((price, i) => {\n * while (!stack.isEmpty() && prices[stack.peek()!] <= price) {\n * stack.pop();\n * }\n * spans.push(stack.isEmpty() ? i + 1 : i - stack.peek()!);\n * stack.push(i);\n * });\n * console.log(spans); // [1, 1, 1, 2, 1, 4, 6]\n */\nexport class Stack<E = any, R = any> extends IterableElementBase<E, R> {\n protected _equals: (a: E, b: E) => boolean = Object.is as unknown as (a: E, b: E) => boolean;\n\n /**\n * Create a Stack and optionally bulk-push elements.\n * @remarks Time O(N), Space O(N)\n * @param [elements] - Iterable of elements (or raw records if toElementFn is set).\n * @param [options] - Options such as toElementFn and equality function.\n * @returns New Stack instance.\n */\n\n constructor(elements: Iterable<E> | Iterable<R> = [], options?: StackOptions<E, R>) {\n super(options);\n this.pushMany(elements);\n }\n\n protected _elements: E[] = [];\n\n /**\n * Get the backing array of elements.\n * @remarks Time O(1), Space O(1)\n * @returns Internal elements array.\n */\n\n get elements(): E[] {\n return this._elements;\n }\n\n /**\n * Get the number of stored elements.\n * @remarks Time O(1), Space O(1)\n * @returns Current size.\n */\n\n get size(): number {\n return this.elements.length;\n }\n\n /**\n * Create a stack from an array of elements.\n * @remarks Time O(N), Space O(N)\n * @template E\n * @template R\n * @param this - The constructor (subclass) to instantiate.\n * @param elements - Array of elements to push in order.\n * @param [options] - Options forwarded to the constructor.\n * @returns A new Stack populated from the array.\n */\n\n static fromArray<E, R = any>(\n this: new (elements?: Iterable<E> | Iterable<R>, options?: StackOptions<E, R>) => any,\n elements: E[],\n options?: StackOptions<E, R>\n ) {\n return new this(elements, options);\n }\n\n /**\n * Check whether the stack 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.elements.length === 0;\n }\n\n /**\n * Get the top element without removing it.\n * @remarks Time O(1), Space O(1)\n * @returns Top element or undefined.\n */\n\n peek(): E | undefined {\n return this.isEmpty() ? undefined : this.elements[this.elements.length - 1];\n }\n\n /**\n * Push one element onto the top.\n * @remarks Time O(1), Space O(1)\n * @param element - Element to push.\n * @returns True when pushed.\n */\n\n push(element: E): boolean {\n this.elements.push(element);\n return true;\n }\n\n /**\n * Pop and return the top element.\n * @remarks Time O(1), Space O(1)\n * @returns Removed element or undefined.\n */\n\n pop(): E | undefined {\n return this.isEmpty() ? undefined : this.elements.pop();\n }\n\n /**\n * Push many elements from an iterable.\n * @remarks Time O(N), Space O(1)\n * @param elements - Iterable of elements (or raw records if toElementFn is set).\n * @returns Array of per-element success flags.\n */\n\n pushMany(elements: Iterable<E> | Iterable<R>): boolean[] {\n const ans: boolean[] = [];\n for (const el of elements) {\n if (this.toElementFn) ans.push(this.push(this.toElementFn(el as R)));\n else ans.push(this.push(el as E));\n }\n return ans;\n }\n\n /**\n * Delete the first occurrence of a specific element.\n * @remarks Time O(N), Space O(1)\n * @param element - Element to remove (using the configured equality).\n * @returns True if an element was removed.\n */\n\n delete(element: E): boolean {\n const idx = this._indexOfByEquals(element);\n return this.deleteAt(idx);\n }\n\n /**\n * Delete the element at an index.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index from the bottom.\n * @returns True if removed.\n */\n\n deleteAt(index: number): boolean {\n if (index < 0 || index >= this.elements.length) return false;\n const spliced = this.elements.splice(index, 1);\n return spliced.length === 1;\n }\n\n /**\n * Delete the first element that satisfies a predicate.\n * @remarks Time O(N), Space O(1)\n * @param predicate - Function (value, index, stack) → boolean to decide deletion.\n * @returns True if a match was removed.\n */\n\n deleteWhere(predicate: (value: E, index: number, stack: this) => boolean): boolean {\n for (let i = 0; i < this.elements.length; i++) {\n if (predicate(this.elements[i], i, this)) {\n this.elements.splice(i, 1);\n return true;\n }\n }\n return false;\n }\n\n /**\n * Remove all elements and reset storage.\n * @remarks Time O(1), Space O(1)\n * @returns void\n */\n\n clear(): void {\n this._elements = [];\n }\n\n /**\n * Deep clone this stack.\n * @remarks Time O(N), Space O(N)\n * @returns A new stack with the same content.\n */\n\n clone(): this {\n const out = this._createInstance({ toElementFn: this.toElementFn });\n for (const v of this) out.push(v);\n return out;\n }\n\n /**\n * Filter elements into a new stack of the same class.\n * @remarks Time O(N), Space O(N)\n * @param predicate - Predicate (value, index, stack) → boolean to keep value.\n * @param [thisArg] - Value for `this` inside the predicate.\n * @returns A new stack with kept values.\n */\n\n filter(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): this {\n const out = this._createInstance({ toElementFn: this.toElementFn });\n let index = 0;\n for (const v of this) {\n if (predicate.call(thisArg, v, index, this)) out.push(v);\n index++;\n }\n return out;\n }\n\n /**\n * Map values into a new stack of the same element type.\n * @remarks Time O(N), Space O(N)\n * @param callback - Mapping function (value, index, stack) → newValue.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new stack with mapped values.\n */\n\n mapSame(callback: ElementCallback<E, R, E>, thisArg?: unknown): this {\n const out = this._createInstance({ toElementFn: this.toElementFn });\n let index = 0;\n for (const v of this) {\n const mv = thisArg === undefined ? callback(v, index++, this) : callback.call(thisArg, v, index++, this);\n out.push(mv);\n }\n return out;\n }\n\n /**\n * Map values into a new stack (possibly different element type).\n * @remarks Time O(N), Space O(N)\n * @template EM\n * @template RM\n * @param callback - Mapping function (value, index, stack) → newElement.\n * @param [options] - Options for the output stack (e.g., toElementFn).\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new Stack with mapped elements.\n */\n\n map<EM, RM>(\n callback: ElementCallback<E, R, EM>,\n options?: IterableElementBaseOptions<EM, RM>,\n thisArg?: unknown\n ): Stack<EM, RM> {\n const out = this._createLike<EM, RM>([], { ...(options ?? {}) });\n let index = 0;\n for (const v of this) {\n out.push(thisArg === undefined ? callback(v, index, this) : callback.call(thisArg, v, index, this));\n index++;\n }\n return out;\n }\n\n /**\n * Set the equality comparator used by delete/search operations.\n * @remarks Time O(1), Space O(1)\n * @param equals - Equality predicate (a, b) → boolean.\n * @returns This stack.\n */\n\n setEquality(equals: (a: E, b: E) => boolean): this {\n this._equals = equals;\n return this;\n }\n\n /**\n * (Protected) Find the index of a target element using the equality function.\n * @remarks Time O(N), Space O(1)\n * @param target - Element to search for.\n * @returns Index or -1 if not found.\n */\n\n protected _indexOfByEquals(target: E): number {\n for (let i = 0; i < this.elements.length; i++) if (this._equals(this.elements[i], target)) return i;\n return -1;\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 stack instance.\n */\n\n protected _createInstance(options?: StackOptions<E, R>): this {\n const Ctor = this.constructor as new (elements?: Iterable<E> | Iterable<R>, options?: StackOptions<E, R>) => this;\n return new Ctor([], options);\n }\n\n /**\n * (Protected) Create a like-kind stack and seed it from an iterable.\n * @remarks Time O(N), Space O(N)\n * @template T\n * @template RR\n * @param [elements] - Iterable used to seed the new stack.\n * @param [options] - Options forwarded to the constructor.\n * @returns A like-kind Stack instance.\n */\n\n protected _createLike<T = E, RR = R>(\n elements: Iterable<T> | Iterable<RR> = [],\n options?: StackOptions<T, RR>\n ): Stack<T, RR> {\n const Ctor = this.constructor as new (\n elements?: Iterable<T> | Iterable<RR>,\n options?: StackOptions<T, RR>\n ) => Stack<T, RR>;\n return new Ctor(elements, options);\n }\n\n /**\n * (Protected) Iterate elements from bottom to top.\n * @remarks Time O(N), Space O(1)\n * @returns Iterator of elements.\n */\n\n protected *_getIterator(): IterableIterator<E> {\n for (let i = 0; i < this.elements.length; i++) yield this.elements[i];\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACaO,MAAe,sBAAf,MAAgE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAU3D,YAAY,SAA4C;AAclE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,0BAAU;AAbR,UAAI,SAAS;AACX,cAAM,EAAE,YAAY,IAAI;AACxB,YAAI,OAAO,gBAAgB,WAAY,MAAK,eAAe;AAAA,iBAClD,YAAa,OAAM,IAAI,UAAU,qCAAqC;AAAA,MACjF;AAAA,IACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAiBA,IAAI,cAAkD;AACpD,aAAO,KAAK;AAAA,IACd;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAWA,EAAE,OAAO,QAAQ,KAAK,MAAsC;AAC1D,aAAO,KAAK,aAAa,GAAG,IAAI;AAAA,IAClC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IASA,CAAC,SAA8B;AAC7B,iBAAW,QAAQ,KAAM,OAAM;AAAA,IACjC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAaA,MAAM,WAA2C,SAA4B;AAC3E,UAAI,QAAQ;AACZ,iBAAW,QAAQ,MAAM;AACvB,YAAI,YAAY,QAAW;AACzB,cAAI,CAAC,UAAU,MAAM,SAAS,IAAI,EAAG,QAAO;AAAA,QAC9C,OAA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,YAAY,KAAK,cAAc,WAAW,KAAK,KAAK,IAAI,KAAK,IAAI,WAAW,KAAK,KAAK,IAAI,IAAI;AACpG,aAAO,YAAY;AAAA,IACrB;AAAA,EACF;","names":["DFSOperation"]}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"use strict";var stackTyped=(()=>{var u=Object.defineProperty;var d=Object.getOwnPropertyDescriptor;var R=Object.getOwnPropertyNames;var x=Object.prototype.hasOwnProperty;var k=(o,t,e)=>t in o?u(o,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[t]=e;var w=(o,t)=>{for(var e in t)u(o,e,{get:t[e],enumerable:!0})},T=(o,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of R(t))!x.call(o,r)&&r!==e&&u(o,r,{get:()=>t[r],enumerable:!(n=d(t,r))||n.enumerable});return o};var g=o=>T(u({},"__esModule",{value:!0}),o);var i=(o,t,e)=>k(o,typeof t!="symbol"?t+"":t,e);var y={};w(y,{DFSOperation:()=>b,Range:()=>E,Stack:()=>m});var c=class{constructor(t){i(this,"_toElementFn");if(t){let{toElementFn:e}=t;if(typeof e=="function")this._toElementFn=e;else if(e)throw new TypeError("toElementFn must be a function type")}}get toElementFn(){return this._toElementFn}*[Symbol.iterator](...t){yield*this._getIterator(...t)}*values(){for(let t of this)yield t}every(t,e){let n=0;for(let r of this)if(e===void 0){if(!t(r,n++,this))return!1}else if(!t.call(e,r,n++,this))return!1;return!0}some(t,e){let n=0;for(let r of this)if(e===void 0){if(t(r,n++,this))return!0}else if(t.call(e,r,n++,this))return!0;return!1}forEach(t,e){let n=0;for(let r of this)e===void 0?t(r,n++,this):t.call(e,r,n++,this)}find(t,e){let n=0;for(let r of this)if(e===void 0){if(t(r,n++,this))return r}else if(t.call(e,r,n++,this))return r}has(t){for(let e of this)if(e===t)return!0;return!1}reduce(t,e){let n=0,r=this[Symbol.iterator](),s;if(arguments.length>=2)s=e;else{let l=r.next();if(l.done)throw new TypeError("Reduce of empty structure with no initial value");s=l.value,n=1}for(let l of r)s=t(s,l,n++,this);return s}toArray(){return[...this]}toVisual(){return[...this]}print(){console.log(this.toVisual())}};var m=class extends c{constructor(e=[],n){super(n);i(this,"_equals",Object.is);i(this,"_elements",[]);this.pushMany(e)}get elements(){return this._elements}get size(){return this.elements.length}static fromArray(e,n){return new this(e,n)}isEmpty(){return this.elements.length===0}peek(){return this.isEmpty()?void 0:this.elements[this.elements.length-1]}push(e){return this.elements.push(e),!0}pop(){return this.isEmpty()?void 0:this.elements.pop()}pushMany(e){let n=[];for(let r of e)this.toElementFn?n.push(this.push(this.toElementFn(r))):n.push(this.push(r));return n}delete(e){let n=this._indexOfByEquals(e);return this.deleteAt(n)}deleteAt(e){return e<0||e>=this.elements.length?!1:this.elements.splice(e,1).length===1}deleteWhere(e){for(let n=0;n<this.elements.length;n++)if(e(this.elements[n],n,this))return this.elements.splice(n,1),!0;return!1}clear(){this._elements=[]}clone(){let e=this._createInstance({toElementFn:this.toElementFn});for(let n of this)e.push(n);return e}filter(e,n){let r=this._createInstance({toElementFn:this.toElementFn}),s=0;for(let l of this)e.call(n,l,s,this)&&r.push(l),s++;return r}mapSame(e,n){let r=this._createInstance({toElementFn:this.toElementFn}),s=0;for(let l of this){let a=n===void 0?e(l,s++,this):e.call(n,l,s++,this);r.push(a)}return r}map(e,n,r){let s=this._createLike([],{...n!=null?n:{}}),l=0;for(let a of this)s.push(r===void 0?e(a,l,this):e.call(r,a,l,this)),l++;return s}setEquality(e){return this._equals=e,this}_indexOfByEquals(e){for(let n=0;n<this.elements.length;n++)if(this._equals(this.elements[n],e))return n;return-1}_createInstance(e){let n=this.constructor;return new n([],e)}_createLike(e=[],n){let r=this.constructor;return new r(e,n)}*_getIterator(){for(let e=0;e<this.elements.length;e++)yield this.elements[e]}};function f(o){let t=typeof o;return t==="number"?!0:t==="bigint"||t==="string"||t==="boolean"}function p(o){if(typeof o.valueOf=="function"){let t=o.valueOf();if(t!==o){if(f(t))return t;if(typeof t=="object"&&t!==null)return p(t)}}if(typeof o.toString=="function"){let t=o.toString();if(t!=="[object Object]")return t}return null}function h(o,t=!1){if(o==null)return!1;if(f(o))return!0;if(typeof o!="object")return!1;if(o instanceof Date||t)return!0;let e=p(o);return e==null?!1:f(e)}var b=(e=>(e[e.VISIT=0]="VISIT",e[e.PROCESS=1]="PROCESS",e))(b||{}),E=class{constructor(t,e,n=!0,r=!0){this.low=t;this.high=e;this.includeLow=n;this.includeHigh=r;if(!(h(t)&&h(e)))throw new RangeError("low or high is not comparable");if(t>e)throw new RangeError("low must be less than or equal to high")}isInRange(t,e){let n=this.includeLow?e(t,this.low)>=0:e(t,this.low)>0,r=this.includeHigh?e(t,this.high)<=0:e(t,this.high)<0;return n&&r}};return g(y);})();
|
|
2
|
+
/**
|
|
3
|
+
* data-structure-typed
|
|
4
|
+
*
|
|
5
|
+
* @author Pablo Zeng
|
|
6
|
+
* @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>
|
|
7
|
+
* @license MIT License
|
|
8
|
+
*/
|
|
9
|
+
//# sourceMappingURL=stack-typed.min.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/index.ts","../../src/data-structures/base/iterable-element-base.ts","../../src/data-structures/stack/stack.ts","../../src/utils/utils.ts","../../src/common/index.ts"],"sourcesContent":["/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\nexport * from './data-structures/stack';\nexport * from './types/data-structures/stack';\nexport * from './types/common';\nexport * from './types/utils';\nexport * from './common';","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, IterableElementBaseOptions, StackOptions } from '../../types';\nimport { IterableElementBase } from '../base';\n\n/**\n * LIFO stack with array storage and optional record→element conversion.\n * @remarks Time O(1), Space O(1)\n * @template E\n * @template R\n * 1. Last In, First Out (LIFO): The core characteristic of a stack is its last in, first out nature, meaning the last element added to the stack will be the first to be removed.\n * 2. Uses: Stacks are commonly used for managing a series of tasks or elements that need to be processed in a last in, first out manner. They are widely used in various scenarios, such as in function calls in programming languages, evaluation of arithmetic expressions, and backtracking algorithms.\n * 3. Performance: Stack operations are typically O(1) in time complexity, meaning that regardless of the stack's size, adding, removing, and viewing the top element are very fast operations.\n * 4. Function Calls: In most modern programming languages, the records of function calls are managed through a stack. When a function is called, its record (including parameters, local variables, and return address) is 'pushed' into the stack. When the function returns, its record is 'popped' from the stack.\n * 5. Expression Evaluation: Used for the evaluation of arithmetic or logical expressions, especially when dealing with parenthesis matching and operator precedence.\n * 6. Backtracking Algorithms: In problems where multiple branches need to be explored but only one branch can be explored at a time, stacks can be used to save the state at each branching point.\n * @example\n * // Balanced Parentheses or Brackets\n * type ValidCharacters = ')' | '(' | ']' | '[' | '}' | '{';\n *\n * const stack = new Stack<string>();\n * const input: ValidCharacters[] = '[({})]'.split('') as ValidCharacters[];\n * const matches: { [key in ValidCharacters]?: ValidCharacters } = { ')': '(', ']': '[', '}': '{' };\n * for (const char of input) {\n * if ('([{'.includes(char)) {\n * stack.push(char);\n * } else if (')]}'.includes(char)) {\n * if (stack.pop() !== matches[char]) {\n * fail('Parentheses are not balanced');\n * }\n * }\n * }\n * console.log(stack.isEmpty()); // true\n * @example\n * // Expression Evaluation and Conversion\n * const stack = new Stack<number>();\n * const expression = [5, 3, '+']; // Equivalent to 5 + 3\n * expression.forEach(token => {\n * if (typeof token === 'number') {\n * stack.push(token);\n * } else {\n * const b = stack.pop()!;\n * const a = stack.pop()!;\n * stack.push(token === '+' ? a + b : 0); // Only handling '+' here\n * }\n * });\n * console.log(stack.pop()); // 8\n * @example\n * // Depth-First Search (DFS)\n * const stack = new Stack<number>();\n * const graph: { [key in number]: number[] } = { 1: [2, 3], 2: [4], 3: [5], 4: [], 5: [] };\n * const visited: number[] = [];\n * stack.push(1);\n * while (!stack.isEmpty()) {\n * const node = stack.pop()!;\n * if (!visited.includes(node)) {\n * visited.push(node);\n * graph[node].forEach(neighbor => stack.push(neighbor));\n * }\n * }\n * console.log(visited); // [1, 3, 5, 2, 4]\n * @example\n * // Backtracking Algorithms\n * const stack = new Stack<[number, number]>();\n * const maze = [\n * ['S', ' ', 'X'],\n * ['X', ' ', 'X'],\n * [' ', ' ', 'E']\n * ];\n * const start: [number, number] = [0, 0];\n * const end = [2, 2];\n * const directions = [\n * [0, 1], // To the right\n * [1, 0], // down\n * [0, -1], // left\n * [-1, 0] // up\n * ];\n *\n * const visited = new Set<string>(); // Used to record visited nodes\n * stack.push(start);\n * const path: number[][] = [];\n *\n * while (!stack.isEmpty()) {\n * const [x, y] = stack.pop()!;\n * if (visited.has(`${x},${y}`)) continue; // Skip already visited nodes\n * visited.add(`${x},${y}`);\n *\n * path.push([x, y]);\n *\n * if (x === end[0] && y === end[1]) {\n * break; // Find the end point and exit\n * }\n *\n * for (const [dx, dy] of directions) {\n * const nx = x + dx;\n * const ny = y + dy;\n * if (\n * maze[nx]?.[ny] === ' ' || // feasible path\n * maze[nx]?.[ny] === 'E' // destination\n * ) {\n * stack.push([nx, ny]);\n * }\n * }\n * }\n *\n * expect(path).toContainEqual(end);\n * @example\n * // Function Call Stack\n * const functionStack = new Stack<string>();\n * functionStack.push('main');\n * functionStack.push('foo');\n * functionStack.push('bar');\n * console.log(functionStack.pop()); // 'bar'\n * console.log(functionStack.pop()); // 'foo'\n * console.log(functionStack.pop()); // 'main'\n * @example\n * // Simplify File Paths\n * const stack = new Stack<string>();\n * const path = '/a/./b/../../c';\n * path.split('/').forEach(segment => {\n * if (segment === '..') stack.pop();\n * else if (segment && segment !== '.') stack.push(segment);\n * });\n * console.log(stack.elements.join('/')); // 'c'\n * @example\n * // Stock Span Problem\n * const stack = new Stack<number>();\n * const prices = [100, 80, 60, 70, 60, 75, 85];\n * const spans: number[] = [];\n * prices.forEach((price, i) => {\n * while (!stack.isEmpty() && prices[stack.peek()!] <= price) {\n * stack.pop();\n * }\n * spans.push(stack.isEmpty() ? i + 1 : i - stack.peek()!);\n * stack.push(i);\n * });\n * console.log(spans); // [1, 1, 1, 2, 1, 4, 6]\n */\nexport class Stack<E = any, R = any> extends IterableElementBase<E, R> {\n protected _equals: (a: E, b: E) => boolean = Object.is as unknown as (a: E, b: E) => boolean;\n\n /**\n * Create a Stack and optionally bulk-push elements.\n * @remarks Time O(N), Space O(N)\n * @param [elements] - Iterable of elements (or raw records if toElementFn is set).\n * @param [options] - Options such as toElementFn and equality function.\n * @returns New Stack instance.\n */\n\n constructor(elements: Iterable<E> | Iterable<R> = [], options?: StackOptions<E, R>) {\n super(options);\n this.pushMany(elements);\n }\n\n protected _elements: E[] = [];\n\n /**\n * Get the backing array of elements.\n * @remarks Time O(1), Space O(1)\n * @returns Internal elements array.\n */\n\n get elements(): E[] {\n return this._elements;\n }\n\n /**\n * Get the number of stored elements.\n * @remarks Time O(1), Space O(1)\n * @returns Current size.\n */\n\n get size(): number {\n return this.elements.length;\n }\n\n /**\n * Create a stack from an array of elements.\n * @remarks Time O(N), Space O(N)\n * @template E\n * @template R\n * @param this - The constructor (subclass) to instantiate.\n * @param elements - Array of elements to push in order.\n * @param [options] - Options forwarded to the constructor.\n * @returns A new Stack populated from the array.\n */\n\n static fromArray<E, R = any>(\n this: new (elements?: Iterable<E> | Iterable<R>, options?: StackOptions<E, R>) => any,\n elements: E[],\n options?: StackOptions<E, R>\n ) {\n return new this(elements, options);\n }\n\n /**\n * Check whether the stack 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.elements.length === 0;\n }\n\n /**\n * Get the top element without removing it.\n * @remarks Time O(1), Space O(1)\n * @returns Top element or undefined.\n */\n\n peek(): E | undefined {\n return this.isEmpty() ? undefined : this.elements[this.elements.length - 1];\n }\n\n /**\n * Push one element onto the top.\n * @remarks Time O(1), Space O(1)\n * @param element - Element to push.\n * @returns True when pushed.\n */\n\n push(element: E): boolean {\n this.elements.push(element);\n return true;\n }\n\n /**\n * Pop and return the top element.\n * @remarks Time O(1), Space O(1)\n * @returns Removed element or undefined.\n */\n\n pop(): E | undefined {\n return this.isEmpty() ? undefined : this.elements.pop();\n }\n\n /**\n * Push many elements from an iterable.\n * @remarks Time O(N), Space O(1)\n * @param elements - Iterable of elements (or raw records if toElementFn is set).\n * @returns Array of per-element success flags.\n */\n\n pushMany(elements: Iterable<E> | Iterable<R>): boolean[] {\n const ans: boolean[] = [];\n for (const el of elements) {\n if (this.toElementFn) ans.push(this.push(this.toElementFn(el as R)));\n else ans.push(this.push(el as E));\n }\n return ans;\n }\n\n /**\n * Delete the first occurrence of a specific element.\n * @remarks Time O(N), Space O(1)\n * @param element - Element to remove (using the configured equality).\n * @returns True if an element was removed.\n */\n\n delete(element: E): boolean {\n const idx = this._indexOfByEquals(element);\n return this.deleteAt(idx);\n }\n\n /**\n * Delete the element at an index.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index from the bottom.\n * @returns True if removed.\n */\n\n deleteAt(index: number): boolean {\n if (index < 0 || index >= this.elements.length) return false;\n const spliced = this.elements.splice(index, 1);\n return spliced.length === 1;\n }\n\n /**\n * Delete the first element that satisfies a predicate.\n * @remarks Time O(N), Space O(1)\n * @param predicate - Function (value, index, stack) → boolean to decide deletion.\n * @returns True if a match was removed.\n */\n\n deleteWhere(predicate: (value: E, index: number, stack: this) => boolean): boolean {\n for (let i = 0; i < this.elements.length; i++) {\n if (predicate(this.elements[i], i, this)) {\n this.elements.splice(i, 1);\n return true;\n }\n }\n return false;\n }\n\n /**\n * Remove all elements and reset storage.\n * @remarks Time O(1), Space O(1)\n * @returns void\n */\n\n clear(): void {\n this._elements = [];\n }\n\n /**\n * Deep clone this stack.\n * @remarks Time O(N), Space O(N)\n * @returns A new stack with the same content.\n */\n\n clone(): this {\n const out = this._createInstance({ toElementFn: this.toElementFn });\n for (const v of this) out.push(v);\n return out;\n }\n\n /**\n * Filter elements into a new stack of the same class.\n * @remarks Time O(N), Space O(N)\n * @param predicate - Predicate (value, index, stack) → boolean to keep value.\n * @param [thisArg] - Value for `this` inside the predicate.\n * @returns A new stack with kept values.\n */\n\n filter(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): this {\n const out = this._createInstance({ toElementFn: this.toElementFn });\n let index = 0;\n for (const v of this) {\n if (predicate.call(thisArg, v, index, this)) out.push(v);\n index++;\n }\n return out;\n }\n\n /**\n * Map values into a new stack of the same element type.\n * @remarks Time O(N), Space O(N)\n * @param callback - Mapping function (value, index, stack) → newValue.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new stack with mapped values.\n */\n\n mapSame(callback: ElementCallback<E, R, E>, thisArg?: unknown): this {\n const out = this._createInstance({ toElementFn: this.toElementFn });\n let index = 0;\n for (const v of this) {\n const mv = thisArg === undefined ? callback(v, index++, this) : callback.call(thisArg, v, index++, this);\n out.push(mv);\n }\n return out;\n }\n\n /**\n * Map values into a new stack (possibly different element type).\n * @remarks Time O(N), Space O(N)\n * @template EM\n * @template RM\n * @param callback - Mapping function (value, index, stack) → newElement.\n * @param [options] - Options for the output stack (e.g., toElementFn).\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new Stack with mapped elements.\n */\n\n map<EM, RM>(\n callback: ElementCallback<E, R, EM>,\n options?: IterableElementBaseOptions<EM, RM>,\n thisArg?: unknown\n ): Stack<EM, RM> {\n const out = this._createLike<EM, RM>([], { ...(options ?? {}) });\n let index = 0;\n for (const v of this) {\n out.push(thisArg === undefined ? callback(v, index, this) : callback.call(thisArg, v, index, this));\n index++;\n }\n return out;\n }\n\n /**\n * Set the equality comparator used by delete/search operations.\n * @remarks Time O(1), Space O(1)\n * @param equals - Equality predicate (a, b) → boolean.\n * @returns This stack.\n */\n\n setEquality(equals: (a: E, b: E) => boolean): this {\n this._equals = equals;\n return this;\n }\n\n /**\n * (Protected) Find the index of a target element using the equality function.\n * @remarks Time O(N), Space O(1)\n * @param target - Element to search for.\n * @returns Index or -1 if not found.\n */\n\n protected _indexOfByEquals(target: E): number {\n for (let i = 0; i < this.elements.length; i++) if (this._equals(this.elements[i], target)) return i;\n return -1;\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 stack instance.\n */\n\n protected _createInstance(options?: StackOptions<E, R>): this {\n const Ctor = this.constructor as new (elements?: Iterable<E> | Iterable<R>, options?: StackOptions<E, R>) => this;\n return new Ctor([], options);\n }\n\n /**\n * (Protected) Create a like-kind stack and seed it from an iterable.\n * @remarks Time O(N), Space O(N)\n * @template T\n * @template RR\n * @param [elements] - Iterable used to seed the new stack.\n * @param [options] - Options forwarded to the constructor.\n * @returns A like-kind Stack instance.\n */\n\n protected _createLike<T = E, RR = R>(\n elements: Iterable<T> | Iterable<RR> = [],\n options?: StackOptions<T, RR>\n ): Stack<T, RR> {\n const Ctor = this.constructor as new (\n elements?: Iterable<T> | Iterable<RR>,\n options?: StackOptions<T, RR>\n ) => Stack<T, RR>;\n return new Ctor(elements, options);\n }\n\n /**\n * (Protected) Iterate elements from bottom to top.\n * @remarks Time O(N), Space O(1)\n * @returns Iterator of elements.\n */\n\n protected *_getIterator(): IterableIterator<E> {\n for (let i = 0; i < this.elements.length; i++) yield this.elements[i];\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"],"mappings":"skBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,kBAAAE,EAAA,UAAAC,EAAA,UAAAC,ICaO,IAAeC,EAAf,KAAgE,CAU3D,YAAYC,EAA4C,CAclEC,EAAA,KAAU,gBAbR,GAAID,EAAS,CACX,GAAM,CAAE,YAAAE,CAAY,EAAIF,EACxB,GAAI,OAAOE,GAAgB,WAAY,KAAK,aAAeA,UAClDA,EAAa,MAAM,IAAI,UAAU,qCAAqC,CACjF,CACF,CAiBA,IAAI,aAAkD,CACpD,OAAO,KAAK,YACd,CAWA,EAAE,OAAO,QAAQ,KAAKC,EAAsC,CAC1D,MAAO,KAAK,aAAa,GAAGA,CAAI,CAClC,CASA,CAAC,QAA8B,CAC7B,QAAWC,KAAQ,KAAM,MAAMA,CACjC,CAaA,MAAMC,EAA2CC,EAA4B,CAC3E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/DT,EAAsBS,CAAe,CAC9C,CCpMO,IAAKC,OACVA,IAAA,MAAQ,GAAR,QACAA,IAAA,QAAU,GAAV,UAFUA,OAAA,IAKCC,EAAN,KAAe,CACpB,YACSC,EACAC,EACAC,EAAsB,GACtBC,EAAuB,GAC9B,CAJO,SAAAH,EACA,UAAAC,EACA,gBAAAC,EACA,iBAAAC,EAEP,GAAI,EAAEC,EAAaJ,CAAG,GAAKI,EAAaH,CAAI,GAAI,MAAM,IAAI,WAAW,+BAA+B,EACpG,GAAID,EAAMC,EAAM,MAAM,IAAI,WAAW,wCAAwC,CAC/E,CAGA,UAAUI,EAAQC,EAA6C,CAC7D,IAAMC,EAAW,KAAK,WAAaD,EAAWD,EAAK,KAAK,GAAG,GAAK,EAAIC,EAAWD,EAAK,KAAK,GAAG,EAAI,EAC1FG,EAAY,KAAK,YAAcF,EAAWD,EAAK,KAAK,IAAI,GAAK,EAAIC,EAAWD,EAAK,KAAK,IAAI,EAAI,EACpG,OAAOE,GAAYC,CACrB,CACF","names":["src_exports","__export","DFSOperation","Range","Stack","IterableElementBase","options","__publicField","toElementFn","args","item","predicate","thisArg","index","callbackfn","element","ele","initialValue","iter","acc","first","value","Stack","IterableElementBase","elements","options","__publicField","element","ans","el","idx","index","predicate","i","out","v","thisArg","callback","mv","equals","target","Ctor","isPrimitiveComparable","value","valueType","tryObjectToPrimitive","obj","valueOfResult","stringResult","isComparable","isForceObjectComparable","comparableValue","DFSOperation","Range","low","high","includeLow","includeHigh","isComparable","key","comparator","lowCheck","highCheck"]}
|
package/package.json
CHANGED
|
@@ -1,10 +1,30 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "stack-typed",
|
|
3
|
-
"version": "2.1.
|
|
3
|
+
"version": "2.1.2",
|
|
4
4
|
"description": "Stack",
|
|
5
|
-
"
|
|
5
|
+
"browser": "dist/umd/stack-typed.min.js",
|
|
6
|
+
"umd:main": "dist/umd/stack-typed.min.js",
|
|
7
|
+
"main": "dist/cjs/index.cjs",
|
|
8
|
+
"module": "dist/esm/index.mjs",
|
|
9
|
+
"types": "dist/types/index.d.ts",
|
|
10
|
+
"exports": {
|
|
11
|
+
".": {
|
|
12
|
+
"types": "./dist/types/index.d.ts",
|
|
13
|
+
"import": "./dist/esm/index.mjs",
|
|
14
|
+
"require": "./dist/cjs/index.cjs"
|
|
15
|
+
}
|
|
16
|
+
},
|
|
17
|
+
"sideEffects": false,
|
|
18
|
+
"engines": {
|
|
19
|
+
"node": ">=12.20.0",
|
|
20
|
+
"npm": ">=6.14.0"
|
|
21
|
+
},
|
|
6
22
|
"scripts": {
|
|
7
|
-
"build": "
|
|
23
|
+
"build": "npm run build:ecu",
|
|
24
|
+
"build:node": "tsup --config tsup.node.config.js",
|
|
25
|
+
"build:types": "rm -rf dist/types && tsc -p tsconfig.types.json",
|
|
26
|
+
"build:umd": "tsup",
|
|
27
|
+
"build:ecu": "npm run build:node && npm run build:types && npm run build:umd",
|
|
8
28
|
"lint": "eslint --fix \"src/**/*.{js,ts}\"",
|
|
9
29
|
"format": "prettier --write \"src/**/*.{js,ts}\"",
|
|
10
30
|
"test": "jest",
|
|
@@ -47,7 +67,6 @@
|
|
|
47
67
|
"url": "https://github.com/zrwusa/data-structure-typed/issues"
|
|
48
68
|
},
|
|
49
69
|
"homepage": "https://data-structure-typed-docs.vercel.app",
|
|
50
|
-
"types": "dist/index.d.ts",
|
|
51
70
|
"devDependencies": {
|
|
52
71
|
"@types/jest": "^29.5.3",
|
|
53
72
|
"@types/node": "^20.4.9",
|
|
@@ -61,10 +80,11 @@
|
|
|
61
80
|
"jest": "^29.6.2",
|
|
62
81
|
"prettier": "^3.0.3",
|
|
63
82
|
"ts-jest": "^29.1.1",
|
|
83
|
+
"tsup": "^8.5.1",
|
|
64
84
|
"typedoc": "^0.25.1",
|
|
65
85
|
"typescript": "^4.9.5"
|
|
66
86
|
},
|
|
67
87
|
"dependencies": {
|
|
68
|
-
"data-structure-typed": "^2.1.
|
|
88
|
+
"data-structure-typed": "^2.1.2"
|
|
69
89
|
}
|
|
70
90
|
}
|
|
@@ -130,7 +130,7 @@ export class AVLTreeCounter<K = any, V = any, R = any> extends AVLTree<K, V, R>
|
|
|
130
130
|
return sum;
|
|
131
131
|
}
|
|
132
132
|
|
|
133
|
-
override
|
|
133
|
+
override createNode(key: K, value?: V, count?: number): AVLTreeCounterNode<K, V> {
|
|
134
134
|
return new AVLTreeCounterNode(key, this._isMapMode ? undefined : value, count) as AVLTreeCounterNode<K, V>;
|
|
135
135
|
}
|
|
136
136
|
|
|
@@ -391,10 +391,10 @@ export class AVLTreeCounter<K = any, V = any, R = any> extends AVLTree<K, V, R>
|
|
|
391
391
|
const [key, entryValue] = keyNodeOrEntry;
|
|
392
392
|
if (key === undefined || key === null) return [undefined, undefined];
|
|
393
393
|
const finalValue = value ?? entryValue;
|
|
394
|
-
return [this.
|
|
394
|
+
return [this.createNode(key, finalValue, count), finalValue];
|
|
395
395
|
}
|
|
396
396
|
|
|
397
|
-
return [this.
|
|
397
|
+
return [this.createNode(keyNodeOrEntry, value, count), value];
|
|
398
398
|
}
|
|
399
399
|
|
|
400
400
|
/**
|
|
@@ -412,7 +412,7 @@ export class AVLTreeCounter<K = any, V = any, R = any> extends AVLTree<K, V, R>
|
|
|
412
412
|
destNode = this.ensureNode(destNode);
|
|
413
413
|
if (srcNode && destNode) {
|
|
414
414
|
const { key, value, count, height } = destNode;
|
|
415
|
-
const tempNode = this.
|
|
415
|
+
const tempNode = this.createNode(key, value, count);
|
|
416
416
|
if (tempNode) {
|
|
417
417
|
tempNode.height = height;
|
|
418
418
|
|
|
@@ -113,7 +113,7 @@ export class AVLTreeMultiMap<K = any, V = any, R = any> extends AVLTree<K, V[],
|
|
|
113
113
|
}
|
|
114
114
|
}
|
|
115
115
|
|
|
116
|
-
override
|
|
116
|
+
override createNode(key: K, value: V[] = []): AVLTreeMultiMapNode<K, V> {
|
|
117
117
|
return new AVLTreeMultiMapNode<K, V>(key, this._isMapMode ? [] : value);
|
|
118
118
|
}
|
|
119
119
|
|
|
@@ -196,7 +196,7 @@ export class AVLTree<K = any, V = any, R = any> extends BST<K, V, R> implements
|
|
|
196
196
|
* @param [value] - The value for the new node.
|
|
197
197
|
* @returns The newly created AVLTreeNode.
|
|
198
198
|
*/
|
|
199
|
-
override
|
|
199
|
+
override createNode(key: K, value?: V): AVLTreeNode<K, V> {
|
|
200
200
|
return new AVLTreeNode<K, V>(key, this._isMapMode ? undefined : value) as AVLTreeNode<K, V>;
|
|
201
201
|
}
|
|
202
202
|
|
|
@@ -370,7 +370,7 @@ export class AVLTree<K = any, V = any, R = any> extends BST<K, V, R> implements
|
|
|
370
370
|
|
|
371
371
|
if (srcNodeEnsured && destNodeEnsured) {
|
|
372
372
|
const { key, value, height } = destNodeEnsured;
|
|
373
|
-
const tempNode = this.
|
|
373
|
+
const tempNode = this.createNode(key, value);
|
|
374
374
|
|
|
375
375
|
if (tempNode) {
|
|
376
376
|
tempNode.height = height;
|
|
@@ -390,7 +390,7 @@ export class BinaryTree<K = any, V = any, R = any>
|
|
|
390
390
|
* @param [value] - The value for the new node (used if not in Map mode).
|
|
391
391
|
* @returns The newly created node.
|
|
392
392
|
*/
|
|
393
|
-
|
|
393
|
+
createNode(key: K, value?: V): BinaryTreeNode<K, V> {
|
|
394
394
|
return new BinaryTreeNode<K, V>(key, this._isMapMode ? undefined : value);
|
|
395
395
|
}
|
|
396
396
|
|
|
@@ -2019,10 +2019,10 @@ export class BinaryTree<K = any, V = any, R = any>
|
|
|
2019
2019
|
if (key === undefined) return [undefined, undefined];
|
|
2020
2020
|
else if (key === null) return [null, undefined];
|
|
2021
2021
|
const finalValue = value ?? entryValue;
|
|
2022
|
-
return [this.
|
|
2022
|
+
return [this.createNode(key, finalValue), finalValue];
|
|
2023
2023
|
}
|
|
2024
2024
|
|
|
2025
|
-
return [this.
|
|
2025
|
+
return [this.createNode(keyNodeOrEntry, value), value];
|
|
2026
2026
|
}
|
|
2027
2027
|
|
|
2028
2028
|
/**
|
|
@@ -2147,7 +2147,7 @@ export class BinaryTree<K = any, V = any, R = any>
|
|
|
2147
2147
|
|
|
2148
2148
|
if (srcNode && destNode) {
|
|
2149
2149
|
const { key, value } = destNode;
|
|
2150
|
-
const tempNode = this.
|
|
2150
|
+
const tempNode = this.createNode(key, value); // Use a temp node to hold dest properties
|
|
2151
2151
|
|
|
2152
2152
|
if (tempNode) {
|
|
2153
2153
|
// Copy src to dest
|
|
@@ -268,7 +268,7 @@ export class BST<K = any, V = any, R = any> extends BinaryTree<K, V, R> implemen
|
|
|
268
268
|
* @param [value] - The value for the new node (used if not in Map mode).
|
|
269
269
|
* @returns The newly created BSTNode.
|
|
270
270
|
*/
|
|
271
|
-
override
|
|
271
|
+
override createNode(key: K, value?: V): BSTNode<K, V> {
|
|
272
272
|
return new BSTNode<K, V>(key, this._isMapMode ? undefined : value);
|
|
273
273
|
}
|
|
274
274
|
|
|
@@ -89,7 +89,7 @@ export class RedBlackTreeNode<K = any, V = any> extends BSTNode<K, V> {
|
|
|
89
89
|
}
|
|
90
90
|
|
|
91
91
|
/**
|
|
92
|
-
*
|
|
92
|
+
* Represents a Red-Black Tree (self-balancing BST) supporting map-like mode and stable O(log n) updates.
|
|
93
93
|
* @remarks Time O(1), Space O(1)
|
|
94
94
|
* @template K
|
|
95
95
|
* @template V
|
|
@@ -176,7 +176,7 @@ export class RedBlackTree<K = any, V = any, R = any> extends BST<K, V, R> implem
|
|
|
176
176
|
* @param color - See parameter type for details.
|
|
177
177
|
* @returns A new RedBlackTreeNode instance.
|
|
178
178
|
*/
|
|
179
|
-
override
|
|
179
|
+
override createNode(key: K, value?: V, color: RBTNColor = 'BLACK'): RedBlackTreeNode<K, V> {
|
|
180
180
|
return new RedBlackTreeNode<K, V>(key, this._isMapMode ? undefined : value, color);
|
|
181
181
|
}
|
|
182
182
|
|
|
@@ -142,7 +142,7 @@ export class TreeCounter<K = any, V = any, R = any> extends RedBlackTree<K, V, R
|
|
|
142
142
|
return sum;
|
|
143
143
|
}
|
|
144
144
|
|
|
145
|
-
override
|
|
145
|
+
override createNode(key: K, value?: V, color: RBTNColor = 'BLACK', count?: number): TreeCounterNode<K, V> {
|
|
146
146
|
return new TreeCounterNode(key, this._isMapMode ? undefined : value, count, color) as TreeCounterNode<K, V>;
|
|
147
147
|
}
|
|
148
148
|
|
|
@@ -427,10 +427,10 @@ export class TreeCounter<K = any, V = any, R = any> extends RedBlackTree<K, V, R
|
|
|
427
427
|
const [key, entryValue] = keyNodeOrEntry;
|
|
428
428
|
if (key === undefined || key === null) return [undefined, undefined];
|
|
429
429
|
const finalValue = value ?? entryValue;
|
|
430
|
-
return [this.
|
|
430
|
+
return [this.createNode(key, finalValue, 'BLACK', count), finalValue];
|
|
431
431
|
}
|
|
432
432
|
|
|
433
|
-
return [this.
|
|
433
|
+
return [this.createNode(keyNodeOrEntry, value, 'BLACK', count), value];
|
|
434
434
|
}
|
|
435
435
|
|
|
436
436
|
/**
|
|
@@ -448,7 +448,7 @@ export class TreeCounter<K = any, V = any, R = any> extends RedBlackTree<K, V, R
|
|
|
448
448
|
destNode = this.ensureNode(destNode);
|
|
449
449
|
if (srcNode && destNode) {
|
|
450
450
|
const { key, value, count, color } = destNode;
|
|
451
|
-
const tempNode = this.
|
|
451
|
+
const tempNode = this.createNode(key, value, color, count);
|
|
452
452
|
if (tempNode) {
|
|
453
453
|
tempNode.color = color;
|
|
454
454
|
|
|
@@ -270,7 +270,7 @@ export class TreeMultiMap<K = any, V = any, R = any> extends RedBlackTree<K, V[]
|
|
|
270
270
|
}
|
|
271
271
|
}
|
|
272
272
|
|
|
273
|
-
override
|
|
273
|
+
override createNode(key: K, value: V[] = []): TreeMultiMapNode<K, V> {
|
|
274
274
|
return new TreeMultiMapNode<K, V>(key, this._isMapMode ? [] : value);
|
|
275
275
|
}
|
|
276
276
|
|
|
@@ -190,7 +190,7 @@ import { IterableElementBase } from '../base';
|
|
|
190
190
|
* ]);
|
|
191
191
|
* console.log(scheduleTasks(tasks, 2)); // expectedMap
|
|
192
192
|
*/
|
|
193
|
-
export class Heap<E =
|
|
193
|
+
export class Heap<E = any, R = any> extends IterableElementBase<E, R> {
|
|
194
194
|
protected _equals: (a: E, b: E) => boolean = Object.is;
|
|
195
195
|
|
|
196
196
|
/**
|
|
@@ -255,7 +255,7 @@ export class Heap<E = unknown, R = never> extends IterableElementBase<E, R> {
|
|
|
255
255
|
* @returns A new heap instance of this class.
|
|
256
256
|
*/
|
|
257
257
|
|
|
258
|
-
static from<T, R =
|
|
258
|
+
static from<T, R = any, S extends Heap<T, R> = Heap<T, R>>(
|
|
259
259
|
this: new (elements?: Iterable<T | R>, options?: HeapOptions<T, R>) => S,
|
|
260
260
|
elements?: Iterable<T | R>,
|
|
261
261
|
options?: HeapOptions<T, R>
|
|
@@ -273,7 +273,7 @@ export class Heap<E = unknown, R = never> extends IterableElementBase<E, R> {
|
|
|
273
273
|
* @returns A new Heap built from elements.
|
|
274
274
|
*/
|
|
275
275
|
|
|
276
|
-
static heapify<EE =
|
|
276
|
+
static heapify<EE = any, RR = any>(elements: Iterable<EE>, options: HeapOptions<EE, RR>): Heap<EE, RR> {
|
|
277
277
|
return new Heap<EE, RR>(elements, options);
|
|
278
278
|
}
|
|
279
279
|
|
|
@@ -788,7 +788,7 @@ export class FibonacciHeap<E> {
|
|
|
788
788
|
*/
|
|
789
789
|
|
|
790
790
|
push(element: E): this {
|
|
791
|
-
const node = this.
|
|
791
|
+
const node = this.createNode(element);
|
|
792
792
|
node.left = node;
|
|
793
793
|
node.right = node;
|
|
794
794
|
this.mergeWithRoot(node);
|
|
@@ -900,7 +900,7 @@ export class FibonacciHeap<E> {
|
|
|
900
900
|
heapToMerge.clear();
|
|
901
901
|
}
|
|
902
902
|
|
|
903
|
-
|
|
903
|
+
createNode(element: E): FibonacciHeapNode<E> {
|
|
904
904
|
return new FibonacciHeapNode<E>(element);
|
|
905
905
|
}
|
|
906
906
|
|
|
@@ -781,7 +781,7 @@ export class SinglyLinkedList<E = any, R = any> extends LinearLinkedBase<E, R, S
|
|
|
781
781
|
* @returns A new SinglyLinkedListNode instance.
|
|
782
782
|
*/
|
|
783
783
|
|
|
784
|
-
protected
|
|
784
|
+
protected createNode(value: E): SinglyLinkedListNode<E> {
|
|
785
785
|
return new SinglyLinkedListNode<E>(value);
|
|
786
786
|
}
|
|
787
787
|
|
|
@@ -807,7 +807,7 @@ export class SinglyLinkedList<E = any, R = any> extends LinearLinkedBase<E, R, S
|
|
|
807
807
|
|
|
808
808
|
protected _ensureNode(elementOrNode: E | SinglyLinkedListNode<E>) {
|
|
809
809
|
if (this.isNode(elementOrNode)) return elementOrNode;
|
|
810
|
-
return this.
|
|
810
|
+
return this.createNode(elementOrNode);
|
|
811
811
|
}
|
|
812
812
|
|
|
813
813
|
/**
|
|
@@ -32,7 +32,7 @@ export interface IBinaryTree<K = any, V = any, R = any> {
|
|
|
32
32
|
readonly isDuplicate: boolean;
|
|
33
33
|
|
|
34
34
|
// ---- construction / mutation ----
|
|
35
|
-
|
|
35
|
+
createNode(key: K, value?: BinaryTreeNode<K, V>['value']): BinaryTreeNode<K, V>;
|
|
36
36
|
|
|
37
37
|
createTree(options?: Partial<BinaryTreeOptions<K, V, R>>): IBinaryTree<K, V, R>;
|
|
38
38
|
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"allowJs": true,
|
|
4
|
+
"allowSyntheticDefaultImports": true,
|
|
5
|
+
"baseUrl": "./",
|
|
6
|
+
"declaration": true,
|
|
7
|
+
"esModuleInterop": true,
|
|
8
|
+
"inlineSourceMap": false,
|
|
9
|
+
"lib": ["esnext"],
|
|
10
|
+
"listEmittedFiles": false,
|
|
11
|
+
"listFiles": false,
|
|
12
|
+
"noFallthroughCasesInSwitch": true,
|
|
13
|
+
"pretty": true,
|
|
14
|
+
"resolveJsonModule": true,
|
|
15
|
+
"skipLibCheck": true,
|
|
16
|
+
"strict": true,
|
|
17
|
+
"traceResolution": false,
|
|
18
|
+
"noImplicitOverride": true,
|
|
19
|
+
"types": ["node"]
|
|
20
|
+
},
|
|
21
|
+
"compileOnSave": false,
|
|
22
|
+
"exclude": ["node_modules", "dist"]
|
|
23
|
+
}
|