stack-typed 2.5.3 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/dist/cjs/index.cjs +59 -0
  2. package/dist/cjs/index.cjs.map +1 -1
  3. package/dist/cjs-legacy/index.cjs +59 -0
  4. package/dist/cjs-legacy/index.cjs.map +1 -1
  5. package/dist/esm/index.mjs +59 -0
  6. package/dist/esm/index.mjs.map +1 -1
  7. package/dist/esm-legacy/index.mjs +59 -0
  8. package/dist/esm-legacy/index.mjs.map +1 -1
  9. package/dist/types/data-structures/base/iterable-element-base.d.ts +17 -0
  10. package/dist/types/data-structures/base/linear-base.d.ts +6 -0
  11. package/dist/types/data-structures/binary-tree/avl-tree.d.ts +36 -0
  12. package/dist/types/data-structures/binary-tree/binary-indexed-tree.d.ts +42 -0
  13. package/dist/types/data-structures/binary-tree/binary-tree.d.ts +75 -0
  14. package/dist/types/data-structures/binary-tree/bst.d.ts +72 -0
  15. package/dist/types/data-structures/binary-tree/red-black-tree.d.ts +57 -0
  16. package/dist/types/data-structures/binary-tree/segment-tree.d.ts +18 -0
  17. package/dist/types/data-structures/binary-tree/tree-map.d.ts +375 -0
  18. package/dist/types/data-structures/binary-tree/tree-multi-map.d.ts +389 -0
  19. package/dist/types/data-structures/binary-tree/tree-multi-set.d.ts +330 -0
  20. package/dist/types/data-structures/binary-tree/tree-set.d.ts +438 -0
  21. package/dist/types/data-structures/graph/directed-graph.d.ts +30 -0
  22. package/dist/types/data-structures/graph/undirected-graph.d.ts +27 -0
  23. package/dist/types/data-structures/hash/hash-map.d.ts +33 -0
  24. package/dist/types/data-structures/heap/heap.d.ts +42 -0
  25. package/dist/types/data-structures/linked-list/doubly-linked-list.d.ts +75 -2
  26. package/dist/types/data-structures/linked-list/singly-linked-list.d.ts +45 -0
  27. package/dist/types/data-structures/linked-list/skip-linked-list.d.ts +54 -0
  28. package/dist/types/data-structures/matrix/matrix.d.ts +24 -0
  29. package/dist/types/data-structures/queue/deque.d.ts +90 -1
  30. package/dist/types/data-structures/queue/queue.d.ts +36 -0
  31. package/dist/types/data-structures/stack/stack.d.ts +30 -0
  32. package/dist/types/data-structures/trie/trie.d.ts +36 -0
  33. package/dist/umd/stack-typed.js +59 -0
  34. package/dist/umd/stack-typed.js.map +1 -1
  35. package/dist/umd/stack-typed.min.js +1 -1
  36. package/dist/umd/stack-typed.min.js.map +1 -1
  37. package/package.json +2 -2
  38. package/src/data-structures/base/iterable-element-base.ts +32 -0
  39. package/src/data-structures/base/linear-base.ts +11 -0
  40. package/src/data-structures/binary-tree/avl-tree.ts +36 -0
  41. package/src/data-structures/binary-tree/binary-indexed-tree.ts +42 -0
  42. package/src/data-structures/binary-tree/binary-tree.ts +75 -0
  43. package/src/data-structures/binary-tree/bst.ts +72 -0
  44. package/src/data-structures/binary-tree/red-black-tree.ts +57 -0
  45. package/src/data-structures/binary-tree/segment-tree.ts +18 -0
  46. package/src/data-structures/binary-tree/tree-map.ts +375 -0
  47. package/src/data-structures/binary-tree/tree-multi-map.ts +392 -0
  48. package/src/data-structures/binary-tree/tree-multi-set.ts +336 -0
  49. package/src/data-structures/binary-tree/tree-set.ts +492 -0
  50. package/src/data-structures/graph/directed-graph.ts +30 -0
  51. package/src/data-structures/graph/undirected-graph.ts +27 -0
  52. package/src/data-structures/hash/hash-map.ts +33 -0
  53. package/src/data-structures/heap/heap.ts +42 -0
  54. package/src/data-structures/linked-list/doubly-linked-list.ts +90 -2
  55. package/src/data-structures/linked-list/singly-linked-list.ts +45 -0
  56. package/src/data-structures/linked-list/skip-linked-list.ts +54 -0
  57. package/src/data-structures/matrix/matrix.ts +24 -0
  58. package/src/data-structures/queue/deque.ts +103 -1
  59. package/src/data-structures/queue/queue.ts +36 -0
  60. package/src/data-structures/stack/stack.ts +30 -0
  61. package/src/data-structures/trie/trie.ts +36 -0
@@ -253,6 +253,9 @@ export declare class Trie<R = any> extends IterableElementBase<string, R> {
253
253
 
254
254
 
255
255
 
256
+
257
+
258
+
256
259
 
257
260
 
258
261
 
@@ -311,6 +314,9 @@ export declare class Trie<R = any> extends IterableElementBase<string, R> {
311
314
 
312
315
 
313
316
 
317
+
318
+
319
+
314
320
 
315
321
 
316
322
 
@@ -364,6 +370,9 @@ export declare class Trie<R = any> extends IterableElementBase<string, R> {
364
370
 
365
371
 
366
372
 
373
+
374
+
375
+
367
376
 
368
377
 
369
378
 
@@ -413,6 +422,9 @@ export declare class Trie<R = any> extends IterableElementBase<string, R> {
413
422
 
414
423
 
415
424
 
425
+
426
+
427
+
416
428
 
417
429
 
418
430
 
@@ -461,6 +473,9 @@ export declare class Trie<R = any> extends IterableElementBase<string, R> {
461
473
 
462
474
 
463
475
 
476
+
477
+
478
+
464
479
 
465
480
 
466
481
 
@@ -512,6 +527,9 @@ export declare class Trie<R = any> extends IterableElementBase<string, R> {
512
527
 
513
528
 
514
529
 
530
+
531
+
532
+
515
533
 
516
534
 
517
535
 
@@ -588,6 +606,9 @@ export declare class Trie<R = any> extends IterableElementBase<string, R> {
588
606
 
589
607
 
590
608
 
609
+
610
+
611
+
591
612
 
592
613
 
593
614
 
@@ -647,6 +668,9 @@ export declare class Trie<R = any> extends IterableElementBase<string, R> {
647
668
 
648
669
 
649
670
 
671
+
672
+
673
+
650
674
 
651
675
 
652
676
 
@@ -700,6 +724,9 @@ export declare class Trie<R = any> extends IterableElementBase<string, R> {
700
724
 
701
725
 
702
726
 
727
+
728
+
729
+
703
730
 
704
731
 
705
732
 
@@ -753,6 +780,9 @@ export declare class Trie<R = any> extends IterableElementBase<string, R> {
753
780
 
754
781
 
755
782
 
783
+
784
+
785
+
756
786
 
757
787
 
758
788
 
@@ -803,6 +833,9 @@ export declare class Trie<R = any> extends IterableElementBase<string, R> {
803
833
 
804
834
 
805
835
 
836
+
837
+
838
+
806
839
 
807
840
 
808
841
 
@@ -848,6 +881,9 @@ export declare class Trie<R = any> extends IterableElementBase<string, R> {
848
881
 
849
882
 
850
883
 
884
+
885
+
886
+
851
887
 
852
888
 
853
889
 
@@ -230,6 +230,35 @@ var stackTyped = (() => {
230
230
  for (const ele of this) if (ele === element) return true;
231
231
  return false;
232
232
  }
233
+ /**
234
+ * Check whether a value exists (Array-compatible alias for `has`).
235
+ * @remarks Provided for familiarity when migrating from Array. Time O(n), Space O(1).
236
+ * @param element - Element to search for (uses `===`).
237
+ * @returns `true` if found.
238
+ */
239
+ includes(element) {
240
+ return this.has(element);
241
+ }
242
+ /**
243
+ * Return an iterator of `[index, value]` pairs (Array-compatible).
244
+ * @remarks Provided for familiarity when migrating from Array. Time O(n), Space O(1) per step.
245
+ */
246
+ *entries() {
247
+ let index = 0;
248
+ for (const value of this) {
249
+ yield [index++, value];
250
+ }
251
+ }
252
+ /**
253
+ * Return an iterator of numeric indices (Array-compatible).
254
+ * @remarks Provided for familiarity when migrating from Array. Time O(n), Space O(1) per step.
255
+ */
256
+ *keys() {
257
+ let index = 0;
258
+ for (const _ of this) {
259
+ yield index++;
260
+ }
261
+ }
233
262
  /**
234
263
  * Reduces all elements to a single accumulated value.
235
264
  *
@@ -361,6 +390,9 @@ var stackTyped = (() => {
361
390
 
362
391
 
363
392
 
393
+
394
+
395
+
364
396
 
365
397
 
366
398
 
@@ -425,6 +457,9 @@ var stackTyped = (() => {
425
457
 
426
458
 
427
459
 
460
+
461
+
462
+
428
463
 
429
464
 
430
465
 
@@ -478,6 +513,9 @@ var stackTyped = (() => {
478
513
 
479
514
 
480
515
 
516
+
517
+
518
+
481
519
 
482
520
 
483
521
 
@@ -531,6 +569,9 @@ var stackTyped = (() => {
531
569
 
532
570
 
533
571
 
572
+
573
+
574
+
534
575
 
535
576
 
536
577
 
@@ -593,6 +634,9 @@ var stackTyped = (() => {
593
634
 
594
635
 
595
636
 
637
+
638
+
639
+
596
640
 
597
641
 
598
642
 
@@ -670,6 +714,9 @@ var stackTyped = (() => {
670
714
 
671
715
 
672
716
 
717
+
718
+
719
+
673
720
 
674
721
 
675
722
 
@@ -747,6 +794,9 @@ var stackTyped = (() => {
747
794
 
748
795
 
749
796
 
797
+
798
+
799
+
750
800
 
751
801
 
752
802
 
@@ -797,6 +847,9 @@ var stackTyped = (() => {
797
847
 
798
848
 
799
849
 
850
+
851
+
852
+
800
853
 
801
854
 
802
855
 
@@ -853,6 +906,9 @@ var stackTyped = (() => {
853
906
 
854
907
 
855
908
 
909
+
910
+
911
+
856
912
 
857
913
 
858
914
 
@@ -929,6 +985,9 @@ var stackTyped = (() => {
929
985
 
930
986
 
931
987
 
988
+
989
+
990
+
932
991
 
933
992
 
934
993
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/index.ts","../../src/common/error.ts","../../src/common/index.ts","../../src/data-structures/base/iterable-element-base.ts","../../src/data-structures/stack/stack.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';","/**\n * Centralized error dispatch.\n * All library errors go through this function for consistent messaging and easy grep.\n * @remarks Always throws — data structure errors are never recoverable.\n * @param ErrorClass - The error constructor (Error, TypeError, RangeError, etc.)\n * @param message - The error message.\n */\nexport function raise(\n ErrorClass: new (msg: string) => Error,\n message: string\n): never {\n throw new ErrorClass(message);\n}\n\n/**\n * Centralized error message templates.\n * Keep using native Error/TypeError/RangeError — this only standardizes messages.\n */\nexport const ERR = {\n // Range / index\n indexOutOfRange: (index: number, min: number, max: number, ctx?: string) =>\n `${ctx ? ctx + ': ' : ''}Index ${index} is out of range [${min}, ${max}].`,\n\n invalidIndex: (ctx?: string) =>\n `${ctx ? ctx + ': ' : ''}Index must be an integer.`,\n\n // Type / argument\n invalidArgument: (reason: string, ctx?: string) =>\n `${ctx ? ctx + ': ' : ''}${reason}`,\n\n comparatorRequired: (ctx?: string) =>\n `${ctx ? ctx + ': ' : ''}Comparator is required for non-number/non-string/non-Date keys.`,\n\n invalidKey: (reason: string, ctx?: string) =>\n `${ctx ? ctx + ': ' : ''}${reason}`,\n\n notAFunction: (name: string, ctx?: string) =>\n `${ctx ? ctx + ': ' : ''}${name} must be a function.`,\n\n invalidEntry: (ctx?: string) =>\n `${ctx ? ctx + ': ' : ''}Each entry must be a [key, value] tuple.`,\n\n invalidNaN: (ctx?: string) =>\n `${ctx ? ctx + ': ' : ''}NaN is not a valid key.`,\n\n invalidDate: (ctx?: string) =>\n `${ctx ? ctx + ': ' : ''}Invalid Date key.`,\n\n reduceEmpty: (ctx?: string) =>\n `${ctx ? ctx + ': ' : ''}Reduce of empty structure with no initial value.`,\n\n callbackReturnType: (expected: string, got: string, ctx?: string) =>\n `${ctx ? ctx + ': ' : ''}Callback must return ${expected}; got ${got}.`,\n\n // State / operation\n invalidOperation: (reason: string, ctx?: string) =>\n `${ctx ? ctx + ': ' : ''}${reason}`,\n\n // Matrix\n matrixDimensionMismatch: (op: string) =>\n `Matrix: Dimensions must be compatible for ${op}.`,\n\n matrixSingular: () =>\n 'Matrix: Singular matrix, inverse does not exist.',\n\n matrixNotSquare: () =>\n 'Matrix: Must be square for inversion.',\n\n matrixNotRectangular: () =>\n 'Matrix: Must be rectangular for transposition.',\n\n matrixRowMismatch: (expected: number, got: number) =>\n `Matrix: Expected row length ${expected}, but got ${got}.`,\n\n // Order statistic\n orderStatisticNotEnabled: (method: string, ctx?: string) =>\n `${ctx ? ctx + ': ' : ''}${method}() requires enableOrderStatistic: true.`\n} as const;\n","export { ERR, raise } from './error';\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","import type { ElementCallback, IterableElementBaseOptions, ReduceElementCallback } from '../../types';\nimport { raise } from '../../common';\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) raise(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) raise(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 * // 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 * // 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 * // 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 * console.log(path); // contains end;\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 * @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 * // Convert stack to array\n * const stack = new Stack<number>([1, 2, 3]);\n * console.log(stack.toArray()); // [1, 2, 3];\n */\nexport class Stack<E = any, R = any> extends IterableElementBase<E, R> {\n protected _equals: (a: E, b: E) => boolean = (a, b) => Object.is(a, b);\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 \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n * @example\n * // Get number of elements\n * const stack = new Stack<number>([1, 2, 3]);\n * console.log(stack.size); // 3;\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 \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n * @example\n * // Check if stack has elements\n * const stack = new Stack<number>();\n * console.log(stack.isEmpty()); // true;\n * stack.push(1);\n * console.log(stack.isEmpty()); // false;\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 \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n * @example\n * // View the top element without removing it\n * const stack = new Stack<string>(['a', 'b', 'c']);\n * console.log(stack.peek()); // 'c';\n * console.log(stack.size); // 3;\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 \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n * @example\n * // basic Stack creation and push operation\n * // Create a simple Stack with initial values\n * const stack = new Stack([1, 2, 3, 4, 5]);\n *\n * // Verify the stack maintains insertion order (LIFO will be shown in pop)\n * console.log([...stack]); // [1, 2, 3, 4, 5];\n *\n * // Check length\n * console.log(stack.size); // 5;\n *\n * // Push a new element to the top\n * stack.push(6);\n * console.log(stack.size); // 6;\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 \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n * @example\n * // Stack pop operation (LIFO - Last In First Out)\n * const stack = new Stack<number>([10, 20, 30, 40, 50]);\n *\n * // Peek at the top element without removing\n * const top = stack.peek();\n * console.log(top); // 50;\n *\n * // Pop removes from the top (LIFO order)\n * const popped = stack.pop();\n * console.log(popped); // 50;\n *\n * // Next pop gets the previous element\n * const next = stack.pop();\n * console.log(next); // 40;\n *\n * // Verify length decreased\n * console.log(stack.size); // 3;\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 \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n * @example\n * // Remove element\n * const stack = new Stack<number>([1, 2, 3]);\n * stack.delete(2);\n * console.log(stack.toArray()); // [1, 3];\n */\n\n delete(element: E): boolean {\n const idx = this._indexOfByEquals(element);\n return this.deleteAt(idx) !== undefined;\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 The removed element, or undefined if the index is out of range.\n */\n\n deleteAt(index: number): E | undefined {\n if (index < 0 || index >= this.elements.length) return undefined;\n const spliced = this.elements.splice(index, 1);\n return spliced[0];\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 \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n * @example\n * // Remove all elements\n * const stack = new Stack<number>([1, 2, 3]);\n * stack.clear();\n * console.log(stack.isEmpty()); // true;\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 \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n * @example\n * // Create independent copy\n * const stack = new Stack<number>([1, 2, 3]);\n * const copy = stack.clone();\n * copy.pop();\n * console.log(stack.size); // 3;\n * console.log(copy.size); // 2;\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 \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n * @example\n * // Filter elements\n * const stack = new Stack<number>([1, 2, 3, 4, 5]);\n * const evens = stack.filter(x => x % 2 === 0);\n * console.log(evens.toArray()); // [2, 4];\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 \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n * @example\n * // Transform elements\n * const stack = new Stack<number>([1, 2, 3]);\n * const doubled = stack.map(x => x * 2);\n * console.log(doubled.toArray()); // [2, 4, 6];\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACOO,WAAS,MACd,YACA,SACO;AACP,UAAM,IAAI,WAAW,OAAO;AAAA,EAC9B;AAMO,MAAM,MAAM;AAAA;AAAA,IAEjB,iBAAiB,CAAC,OAAe,KAAa,KAAa,QACzD,GAAG,MAAM,MAAM,OAAO,EAAE,SAAS,KAAK,qBAAqB,GAAG,KAAK,GAAG;AAAA,IAExE,cAAc,CAAC,QACb,GAAG,MAAM,MAAM,OAAO,EAAE;AAAA;AAAA,IAG1B,iBAAiB,CAAC,QAAgB,QAChC,GAAG,MAAM,MAAM,OAAO,EAAE,GAAG,MAAM;AAAA,IAEnC,oBAAoB,CAAC,QACnB,GAAG,MAAM,MAAM,OAAO,EAAE;AAAA,IAE1B,YAAY,CAAC,QAAgB,QAC3B,GAAG,MAAM,MAAM,OAAO,EAAE,GAAG,MAAM;AAAA,IAEnC,cAAc,CAAC,MAAc,QAC3B,GAAG,MAAM,MAAM,OAAO,EAAE,GAAG,IAAI;AAAA,IAEjC,cAAc,CAAC,QACb,GAAG,MAAM,MAAM,OAAO,EAAE;AAAA,IAE1B,YAAY,CAAC,QACX,GAAG,MAAM,MAAM,OAAO,EAAE;AAAA,IAE1B,aAAa,CAAC,QACZ,GAAG,MAAM,MAAM,OAAO,EAAE;AAAA,IAE1B,aAAa,CAAC,QACZ,GAAG,MAAM,MAAM,OAAO,EAAE;AAAA,IAE1B,oBAAoB,CAAC,UAAkB,KAAa,QAClD,GAAG,MAAM,MAAM,OAAO,EAAE,wBAAwB,QAAQ,SAAS,GAAG;AAAA;AAAA,IA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AAU;AACf,aAAO;AAAA,IACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IASU,iBAAiB,QAAmB;AAC5C,eAAS,IAAI,GAAG,IAAI,KAAK,SAAS,QAAQ,IAAK,KAAI,KAAK,QAAQ,KAAK,SAAS,CAAC,GAAG,MAAM,EAAG,QAAO;AAClG,aAAO;AAAA,IACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IASU,gBAAgB,SAAoC;AAC5D,YAAM,OAAO,KAAK;AAClB,aAAO,IAAI,KAAK,CAAC,GAAG,OAAO;AAAA,IAC7B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAYU,YACR,WAAuC,CAAC,GACxC,SACc;AACd,YAAM,OAAO,KAAK;AAIlB,aAAO,IAAI,KAAK,UAAU,OAAO;AAAA,IACnC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAQA,CAAW,eAAoC;AAC7C,eAAS,IAAI,GAAG,IAAI,KAAK,SAAS,QAAQ,IAAK,OAAM,KAAK,SAAS,CAAC;AAAA,IACtE;AAAA,EACF;","names":["DFSOperation"]}
1
+ {"version":3,"sources":["../../src/index.ts","../../src/common/error.ts","../../src/common/index.ts","../../src/data-structures/base/iterable-element-base.ts","../../src/data-structures/stack/stack.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';","/**\n * Centralized error dispatch.\n * All library errors go through this function for consistent messaging and easy grep.\n * @remarks Always throws — data structure errors are never recoverable.\n * @param ErrorClass - The error constructor (Error, TypeError, RangeError, etc.)\n * @param message - The error message.\n */\nexport function raise(\n ErrorClass: new (msg: string) => Error,\n message: string\n): never {\n throw new ErrorClass(message);\n}\n\n/**\n * Centralized error message templates.\n * Keep using native Error/TypeError/RangeError — this only standardizes messages.\n */\nexport const ERR = {\n // Range / index\n indexOutOfRange: (index: number, min: number, max: number, ctx?: string) =>\n `${ctx ? ctx + ': ' : ''}Index ${index} is out of range [${min}, ${max}].`,\n\n invalidIndex: (ctx?: string) =>\n `${ctx ? ctx + ': ' : ''}Index must be an integer.`,\n\n // Type / argument\n invalidArgument: (reason: string, ctx?: string) =>\n `${ctx ? ctx + ': ' : ''}${reason}`,\n\n comparatorRequired: (ctx?: string) =>\n `${ctx ? ctx + ': ' : ''}Comparator is required for non-number/non-string/non-Date keys.`,\n\n invalidKey: (reason: string, ctx?: string) =>\n `${ctx ? ctx + ': ' : ''}${reason}`,\n\n notAFunction: (name: string, ctx?: string) =>\n `${ctx ? ctx + ': ' : ''}${name} must be a function.`,\n\n invalidEntry: (ctx?: string) =>\n `${ctx ? ctx + ': ' : ''}Each entry must be a [key, value] tuple.`,\n\n invalidNaN: (ctx?: string) =>\n `${ctx ? ctx + ': ' : ''}NaN is not a valid key.`,\n\n invalidDate: (ctx?: string) =>\n `${ctx ? ctx + ': ' : ''}Invalid Date key.`,\n\n reduceEmpty: (ctx?: string) =>\n `${ctx ? ctx + ': ' : ''}Reduce of empty structure with no initial value.`,\n\n callbackReturnType: (expected: string, got: string, ctx?: string) =>\n `${ctx ? ctx + ': ' : ''}Callback must return ${expected}; got ${got}.`,\n\n // State / operation\n invalidOperation: (reason: string, ctx?: string) =>\n `${ctx ? ctx + ': ' : ''}${reason}`,\n\n // Matrix\n matrixDimensionMismatch: (op: string) =>\n `Matrix: Dimensions must be compatible for ${op}.`,\n\n matrixSingular: () =>\n 'Matrix: Singular matrix, inverse does not exist.',\n\n matrixNotSquare: () =>\n 'Matrix: Must be square for inversion.',\n\n matrixNotRectangular: () =>\n 'Matrix: Must be rectangular for transposition.',\n\n matrixRowMismatch: (expected: number, got: number) =>\n `Matrix: Expected row length ${expected}, but got ${got}.`,\n\n // Order statistic\n orderStatisticNotEnabled: (method: string, ctx?: string) =>\n `${ctx ? ctx + ': ' : ''}${method}() requires enableOrderStatistic: true.`\n} as const;\n","export { ERR, raise } from './error';\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","import type { ElementCallback, IterableElementBaseOptions, ReduceElementCallback } from '../../types';\nimport { raise } from '../../common';\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) raise(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 /**\n * Check whether a value exists (Array-compatible alias for `has`).\n * @remarks Provided for familiarity when migrating from Array. Time O(n), Space O(1).\n * @param element - Element to search for (uses `===`).\n * @returns `true` if found.\n */\n includes(element: E): boolean {\n return this.has(element);\n }\n\n /**\n * Return an iterator of `[index, value]` pairs (Array-compatible).\n * @remarks Provided for familiarity when migrating from Array. Time O(n), Space O(1) per step.\n */\n *entries(): IterableIterator<[number, E]> {\n let index = 0;\n for (const value of this) {\n yield [index++, value];\n }\n }\n\n /**\n * Return an iterator of numeric indices (Array-compatible).\n * @remarks Provided for familiarity when migrating from Array. Time O(n), Space O(1) per step.\n */\n *keys(): IterableIterator<number> {\n let index = 0;\n for (const _ of this) {\n yield index++;\n }\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) raise(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 * // 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 * // 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 * // 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 * console.log(path); // contains end;\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 * @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 * // Convert stack to array\n * const stack = new Stack<number>([1, 2, 3]);\n * console.log(stack.toArray()); // [1, 2, 3];\n */\nexport class Stack<E = any, R = any> extends IterableElementBase<E, R> {\n protected _equals: (a: E, b: E) => boolean = (a, b) => Object.is(a, b);\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 \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n * @example\n * // Get number of elements\n * const stack = new Stack<number>([1, 2, 3]);\n * console.log(stack.size); // 3;\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 \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n * @example\n * // Check if stack has elements\n * const stack = new Stack<number>();\n * console.log(stack.isEmpty()); // true;\n * stack.push(1);\n * console.log(stack.isEmpty()); // false;\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 \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n * @example\n * // View the top element without removing it\n * const stack = new Stack<string>(['a', 'b', 'c']);\n * console.log(stack.peek()); // 'c';\n * console.log(stack.size); // 3;\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 \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n * @example\n * // basic Stack creation and push operation\n * // Create a simple Stack with initial values\n * const stack = new Stack([1, 2, 3, 4, 5]);\n *\n * // Verify the stack maintains insertion order (LIFO will be shown in pop)\n * console.log([...stack]); // [1, 2, 3, 4, 5];\n *\n * // Check length\n * console.log(stack.size); // 5;\n *\n * // Push a new element to the top\n * stack.push(6);\n * console.log(stack.size); // 6;\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 \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n * @example\n * // Stack pop operation (LIFO - Last In First Out)\n * const stack = new Stack<number>([10, 20, 30, 40, 50]);\n *\n * // Peek at the top element without removing\n * const top = stack.peek();\n * console.log(top); // 50;\n *\n * // Pop removes from the top (LIFO order)\n * const popped = stack.pop();\n * console.log(popped); // 50;\n *\n * // Next pop gets the previous element\n * const next = stack.pop();\n * console.log(next); // 40;\n *\n * // Verify length decreased\n * console.log(stack.size); // 3;\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 \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n * @example\n * // Remove element\n * const stack = new Stack<number>([1, 2, 3]);\n * stack.delete(2);\n * console.log(stack.toArray()); // [1, 3];\n */\n\n delete(element: E): boolean {\n const idx = this._indexOfByEquals(element);\n return this.deleteAt(idx) !== undefined;\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 The removed element, or undefined if the index is out of range.\n */\n\n deleteAt(index: number): E | undefined {\n if (index < 0 || index >= this.elements.length) return undefined;\n const spliced = this.elements.splice(index, 1);\n return spliced[0];\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 \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n * @example\n * // Remove all elements\n * const stack = new Stack<number>([1, 2, 3]);\n * stack.clear();\n * console.log(stack.isEmpty()); // true;\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 \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n * @example\n * // Create independent copy\n * const stack = new Stack<number>([1, 2, 3]);\n * const copy = stack.clone();\n * copy.pop();\n * console.log(stack.size); // 3;\n * console.log(copy.size); // 2;\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 \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n * @example\n * // Filter elements\n * const stack = new Stack<number>([1, 2, 3, 4, 5]);\n * const evens = stack.filter(x => x % 2 === 0);\n * console.log(evens.toArray()); // [2, 4];\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 \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n * @example\n * // Transform elements\n * const stack = new Stack<number>([1, 2, 3]);\n * const doubled = stack.map(x => x * 2);\n * console.log(doubled.toArray()); // [2, 4, 6];\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACOO,WAAS,MACd,YACA,SACO;AACP,UAAM,IAAI,WAAW,OAAO;AAAA,EAC9B;AAMO,MAA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K,YAAY,SAAY,SAAS,GAAG,OAAO,IAAI,IAAI,SAAS,KAAK,SAAS,GAAG,OAAO,IAAI,CAAC;AAClG;AAAA,MACF;AACA,aAAO;AAAA,IACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IASA,YAAY,QAAuC;AACjD,WAAK,UAAU;AACf,aAAO;AAAA,IACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IASU,iBAAiB,QAAmB;AAC5C,eAAS,IAAI,GAAG,IAAI,KAAK,SAAS,QAAQ,IAAK,KAAI,KAAK,QAAQ,KAAK,SAAS,CAAC,GAAG,MAAM,EAAG,QAAO;AAClG,aAAO;AAAA,IACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IASU,gBAAgB,SAAoC;AAC5D,YAAM,OAAO,KAAK;AAClB,aAAO,IAAI,KAAK,CAAC,GAAG,OAAO;AAAA,IAC7B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAYU,YACR,WAAuC,CAAC,GACxC,SACc;AACd,YAAM,OAAO,KAAK;AAIlB,aAAO,IAAI,KAAK,UAAU,OAAO;AAAA,IACnC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAQA,CAAW,eAAoC;AAC7C,eAAS,IAAI,GAAG,IAAI,KAAK,SAAS,QAAQ,IAAK,OAAM,KAAK,SAAS,CAAC;AAAA,IACtE;AAAA,EACF;","names":["DFSOperation"]}
@@ -1,4 +1,4 @@
1
- "use strict";var stackTyped=(()=>{var c=Object.defineProperty;var d=Object.getOwnPropertyDescriptor;var p=Object.getOwnPropertyNames;var R=Object.prototype.hasOwnProperty;var k=(s,t,e)=>t in s?c(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var g=(s,t)=>{for(var e in t)c(s,e,{get:t[e],enumerable:!0})},w=(s,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of p(t))!R.call(s,r)&&r!==e&&c(s,r,{get:()=>t[r],enumerable:!(n=d(t,r))||n.enumerable});return s};var I=s=>w(c({},"__esModule",{value:!0}),s);var o=(s,t,e)=>k(s,typeof t!="symbol"?t+"":t,e);var y={};g(y,{DFSOperation:()=>b,ERR:()=>f,Range:()=>h,Stack:()=>m,raise:()=>a});function a(s,t){throw new s(t)}var f={indexOutOfRange:(s,t,e,n)=>`${n?n+": ":""}Index ${s} is out of range [${t}, ${e}].`,invalidIndex:s=>`${s?s+": ":""}Index must be an integer.`,invalidArgument:(s,t)=>`${t?t+": ":""}${s}`,comparatorRequired:s=>`${s?s+": ":""}Comparator is required for non-number/non-string/non-Date keys.`,invalidKey:(s,t)=>`${t?t+": ":""}${s}`,notAFunction:(s,t)=>`${t?t+": ":""}${s} must be a function.`,invalidEntry:s=>`${s?s+": ":""}Each entry must be a [key, value] tuple.`,invalidNaN:s=>`${s?s+": ":""}NaN is not a valid key.`,invalidDate:s=>`${s?s+": ":""}Invalid Date key.`,reduceEmpty:s=>`${s?s+": ":""}Reduce of empty structure with no initial value.`,callbackReturnType:(s,t,e)=>`${e?e+": ":""}Callback must return ${s}; got ${t}.`,invalidOperation:(s,t)=>`${t?t+": ":""}${s}`,matrixDimensionMismatch:s=>`Matrix: Dimensions must be compatible for ${s}.`,matrixSingular:()=>"Matrix: Singular matrix, inverse does not exist.",matrixNotSquare:()=>"Matrix: Must be square for inversion.",matrixNotRectangular:()=>"Matrix: Must be rectangular for transposition.",matrixRowMismatch:(s,t)=>`Matrix: Expected row length ${s}, but got ${t}.`,orderStatisticNotEnabled:(s,t)=>`${t?t+": ":""}${s}() requires enableOrderStatistic: true.`};var b=(e=>(e[e.VISIT=0]="VISIT",e[e.PROCESS=1]="PROCESS",e))(b||{}),h=class{constructor(t,e,n=!0,r=!0){this.low=t;this.high=e;this.includeLow=n;this.includeHigh=r}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}};var E=class{constructor(t){o(this,"_toElementFn");if(t){let{toElementFn:e}=t;typeof e=="function"?this._toElementFn=e:e&&a(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](),i;if(arguments.length>=2)i=e;else{let l=r.next();l.done&&a(TypeError,"Reduce of empty structure with no initial value"),i=l.value,n=1}for(let l of r)i=t(i,l,n++,this);return i}toArray(){return[...this]}toVisual(){return[...this]}print(){console.log(this.toVisual())}};var m=class extends E{constructor(e=[],n){super(n);o(this,"_equals",(e,n)=>Object.is(e,n));o(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)!==void 0}deleteAt(e){return e<0||e>=this.elements.length?void 0:this.elements.splice(e,1)[0]}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}),i=0;for(let l of this)e.call(n,l,i,this)&&r.push(l),i++;return r}mapSame(e,n){let r=this._createInstance({toElementFn:this.toElementFn}),i=0;for(let l of this){let u=n===void 0?e(l,i++,this):e.call(n,l,i++,this);r.push(u)}return r}map(e,n,r){let i=this._createLike([],{...n!=null?n:{}}),l=0;for(let u of this)i.push(r===void 0?e(u,l,this):e.call(r,u,l,this)),l++;return i}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]}};return I(y);})();
1
+ "use strict";var stackTyped=(()=>{var c=Object.defineProperty;var d=Object.getOwnPropertyDescriptor;var p=Object.getOwnPropertyNames;var R=Object.prototype.hasOwnProperty;var k=(r,t,e)=>t in r?c(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e;var g=(r,t)=>{for(var e in t)c(r,e,{get:t[e],enumerable:!0})},I=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of p(t))!R.call(r,s)&&s!==e&&c(r,s,{get:()=>t[s],enumerable:!(n=d(t,s))||n.enumerable});return r};var w=r=>I(c({},"__esModule",{value:!0}),r);var o=(r,t,e)=>k(r,typeof t!="symbol"?t+"":t,e);var y={};g(y,{DFSOperation:()=>b,ERR:()=>f,Range:()=>E,Stack:()=>m,raise:()=>a});function a(r,t){throw new r(t)}var f={indexOutOfRange:(r,t,e,n)=>`${n?n+": ":""}Index ${r} is out of range [${t}, ${e}].`,invalidIndex:r=>`${r?r+": ":""}Index must be an integer.`,invalidArgument:(r,t)=>`${t?t+": ":""}${r}`,comparatorRequired:r=>`${r?r+": ":""}Comparator is required for non-number/non-string/non-Date keys.`,invalidKey:(r,t)=>`${t?t+": ":""}${r}`,notAFunction:(r,t)=>`${t?t+": ":""}${r} must be a function.`,invalidEntry:r=>`${r?r+": ":""}Each entry must be a [key, value] tuple.`,invalidNaN:r=>`${r?r+": ":""}NaN is not a valid key.`,invalidDate:r=>`${r?r+": ":""}Invalid Date key.`,reduceEmpty:r=>`${r?r+": ":""}Reduce of empty structure with no initial value.`,callbackReturnType:(r,t,e)=>`${e?e+": ":""}Callback must return ${r}; got ${t}.`,invalidOperation:(r,t)=>`${t?t+": ":""}${r}`,matrixDimensionMismatch:r=>`Matrix: Dimensions must be compatible for ${r}.`,matrixSingular:()=>"Matrix: Singular matrix, inverse does not exist.",matrixNotSquare:()=>"Matrix: Must be square for inversion.",matrixNotRectangular:()=>"Matrix: Must be rectangular for transposition.",matrixRowMismatch:(r,t)=>`Matrix: Expected row length ${r}, but got ${t}.`,orderStatisticNotEnabled:(r,t)=>`${t?t+": ":""}${r}() requires enableOrderStatistic: true.`};var b=(e=>(e[e.VISIT=0]="VISIT",e[e.PROCESS=1]="PROCESS",e))(b||{}),E=class{constructor(t,e,n=!0,s=!0){this.low=t;this.high=e;this.includeLow=n;this.includeHigh=s}isInRange(t,e){let n=this.includeLow?e(t,this.low)>=0:e(t,this.low)>0,s=this.includeHigh?e(t,this.high)<=0:e(t,this.high)<0;return n&&s}};var h=class{constructor(t){o(this,"_toElementFn");if(t){let{toElementFn:e}=t;typeof e=="function"?this._toElementFn=e:e&&a(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 s of this)if(e===void 0){if(!t(s,n++,this))return!1}else if(!t.call(e,s,n++,this))return!1;return!0}some(t,e){let n=0;for(let s of this)if(e===void 0){if(t(s,n++,this))return!0}else if(t.call(e,s,n++,this))return!0;return!1}forEach(t,e){let n=0;for(let s of this)e===void 0?t(s,n++,this):t.call(e,s,n++,this)}find(t,e){let n=0;for(let s of this)if(e===void 0){if(t(s,n++,this))return s}else if(t.call(e,s,n++,this))return s}has(t){for(let e of this)if(e===t)return!0;return!1}includes(t){return this.has(t)}*entries(){let t=0;for(let e of this)yield[t++,e]}*keys(){let t=0;for(let e of this)yield t++}reduce(t,e){let n=0,s=this[Symbol.iterator](),i;if(arguments.length>=2)i=e;else{let l=s.next();l.done&&a(TypeError,"Reduce of empty structure with no initial value"),i=l.value,n=1}for(let l of s)i=t(i,l,n++,this);return i}toArray(){return[...this]}toVisual(){return[...this]}print(){console.log(this.toVisual())}};var m=class extends h{constructor(e=[],n){super(n);o(this,"_equals",(e,n)=>Object.is(e,n));o(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 s of e)this.toElementFn?n.push(this.push(this.toElementFn(s))):n.push(this.push(s));return n}delete(e){let n=this._indexOfByEquals(e);return this.deleteAt(n)!==void 0}deleteAt(e){return e<0||e>=this.elements.length?void 0:this.elements.splice(e,1)[0]}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 s=this._createInstance({toElementFn:this.toElementFn}),i=0;for(let l of this)e.call(n,l,i,this)&&s.push(l),i++;return s}mapSame(e,n){let s=this._createInstance({toElementFn:this.toElementFn}),i=0;for(let l of this){let u=n===void 0?e(l,i++,this):e.call(n,l,i++,this);s.push(u)}return s}map(e,n,s){let i=this._createLike([],{...n!=null?n:{}}),l=0;for(let u of this)i.push(s===void 0?e(u,l,this):e.call(s,u,l,this)),l++;return i}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 s=this.constructor;return new s(e,n)}*_getIterator(){for(let e=0;e<this.elements.length;e++)yield this.elements[e]}};return w(y);})();
2
2
  /**
3
3
  * data-structure-typed
4
4
  *