stack-typed 2.5.2 → 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 (63) hide show
  1. package/dist/cjs/index.cjs +103 -4
  2. package/dist/cjs/index.cjs.map +1 -1
  3. package/dist/cjs-legacy/index.cjs +103 -4
  4. package/dist/cjs-legacy/index.cjs.map +1 -1
  5. package/dist/esm/index.mjs +103 -4
  6. package/dist/esm/index.mjs.map +1 -1
  7. package/dist/esm-legacy/index.mjs +103 -4
  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 +86 -2
  12. package/dist/types/data-structures/binary-tree/binary-indexed-tree.d.ts +98 -0
  13. package/dist/types/data-structures/binary-tree/binary-tree.d.ts +191 -15
  14. package/dist/types/data-structures/binary-tree/bst.d.ts +171 -3
  15. package/dist/types/data-structures/binary-tree/red-black-tree.d.ts +136 -8
  16. package/dist/types/data-structures/binary-tree/segment-tree.d.ts +42 -0
  17. package/dist/types/data-structures/binary-tree/tree-map.d.ts +1061 -167
  18. package/dist/types/data-structures/binary-tree/tree-multi-map.d.ts +1232 -355
  19. package/dist/types/data-structures/binary-tree/tree-multi-set.d.ts +916 -194
  20. package/dist/types/data-structures/binary-tree/tree-set.d.ts +1078 -141
  21. package/dist/types/data-structures/graph/directed-graph.d.ts +70 -0
  22. package/dist/types/data-structures/graph/undirected-graph.d.ts +63 -0
  23. package/dist/types/data-structures/hash/hash-map.d.ts +84 -6
  24. package/dist/types/data-structures/heap/heap.d.ts +140 -12
  25. package/dist/types/data-structures/linked-list/doubly-linked-list.d.ts +150 -2
  26. package/dist/types/data-structures/linked-list/singly-linked-list.d.ts +106 -1
  27. package/dist/types/data-structures/linked-list/skip-linked-list.d.ts +126 -0
  28. package/dist/types/data-structures/matrix/matrix.d.ts +56 -0
  29. package/dist/types/data-structures/queue/deque.d.ts +171 -0
  30. package/dist/types/data-structures/queue/queue.d.ts +97 -0
  31. package/dist/types/data-structures/stack/stack.d.ts +72 -2
  32. package/dist/types/data-structures/trie/trie.d.ts +84 -0
  33. package/dist/types/interfaces/binary-tree.d.ts +2 -3
  34. package/dist/umd/stack-typed.js +103 -4
  35. package/dist/umd/stack-typed.js.map +1 -1
  36. package/dist/umd/stack-typed.min.js +1 -1
  37. package/dist/umd/stack-typed.min.js.map +1 -1
  38. package/package.json +2 -2
  39. package/src/data-structures/base/iterable-element-base.ts +32 -0
  40. package/src/data-structures/base/linear-base.ts +11 -0
  41. package/src/data-structures/binary-tree/avl-tree.ts +88 -5
  42. package/src/data-structures/binary-tree/binary-indexed-tree.ts +98 -0
  43. package/src/data-structures/binary-tree/binary-tree.ts +242 -81
  44. package/src/data-structures/binary-tree/bst.ts +173 -7
  45. package/src/data-structures/binary-tree/red-black-tree.ts +139 -15
  46. package/src/data-structures/binary-tree/segment-tree.ts +42 -0
  47. package/src/data-structures/binary-tree/tree-map.ts +948 -36
  48. package/src/data-structures/binary-tree/tree-multi-map.ts +893 -13
  49. package/src/data-structures/binary-tree/tree-multi-set.ts +761 -33
  50. package/src/data-structures/binary-tree/tree-set.ts +1260 -251
  51. package/src/data-structures/graph/directed-graph.ts +71 -1
  52. package/src/data-structures/graph/undirected-graph.ts +64 -1
  53. package/src/data-structures/hash/hash-map.ts +100 -12
  54. package/src/data-structures/heap/heap.ts +149 -19
  55. package/src/data-structures/linked-list/doubly-linked-list.ts +178 -2
  56. package/src/data-structures/linked-list/singly-linked-list.ts +106 -1
  57. package/src/data-structures/linked-list/skip-linked-list.ts +126 -0
  58. package/src/data-structures/matrix/matrix.ts +56 -0
  59. package/src/data-structures/queue/deque.ts +187 -0
  60. package/src/data-structures/queue/queue.ts +109 -0
  61. package/src/data-structures/stack/stack.ts +75 -5
  62. package/src/data-structures/trie/trie.ts +84 -0
  63. package/src/interfaces/binary-tree.ts +1 -9
@@ -245,6 +245,13 @@ export declare class Trie<R = any> extends IterableElementBase<string, R> {
245
245
 
246
246
 
247
247
 
248
+
249
+
250
+
251
+
252
+
253
+
254
+
248
255
 
249
256
 
250
257
 
@@ -299,6 +306,13 @@ export declare class Trie<R = any> extends IterableElementBase<string, R> {
299
306
 
300
307
 
301
308
 
309
+
310
+
311
+
312
+
313
+
314
+
315
+
302
316
 
303
317
 
304
318
 
@@ -348,6 +362,13 @@ export declare class Trie<R = any> extends IterableElementBase<string, R> {
348
362
 
349
363
 
350
364
 
365
+
366
+
367
+
368
+
369
+
370
+
371
+
351
372
 
352
373
 
353
374
 
@@ -393,6 +414,13 @@ export declare class Trie<R = any> extends IterableElementBase<string, R> {
393
414
 
394
415
 
395
416
 
417
+
418
+
419
+
420
+
421
+
422
+
423
+
396
424
 
397
425
 
398
426
 
@@ -437,6 +465,13 @@ export declare class Trie<R = any> extends IterableElementBase<string, R> {
437
465
 
438
466
 
439
467
 
468
+
469
+
470
+
471
+
472
+
473
+
474
+
440
475
 
441
476
 
442
477
 
@@ -484,6 +519,13 @@ export declare class Trie<R = any> extends IterableElementBase<string, R> {
484
519
 
485
520
 
486
521
 
522
+
523
+
524
+
525
+
526
+
527
+
528
+
487
529
 
488
530
 
489
531
 
@@ -556,6 +598,13 @@ export declare class Trie<R = any> extends IterableElementBase<string, R> {
556
598
 
557
599
 
558
600
 
601
+
602
+
603
+
604
+
605
+
606
+
607
+
559
608
 
560
609
 
561
610
 
@@ -611,6 +660,13 @@ export declare class Trie<R = any> extends IterableElementBase<string, R> {
611
660
 
612
661
 
613
662
 
663
+
664
+
665
+
666
+
667
+
668
+
669
+
614
670
 
615
671
 
616
672
 
@@ -660,6 +716,13 @@ export declare class Trie<R = any> extends IterableElementBase<string, R> {
660
716
 
661
717
 
662
718
 
719
+
720
+
721
+
722
+
723
+
724
+
725
+
663
726
 
664
727
 
665
728
 
@@ -709,6 +772,13 @@ export declare class Trie<R = any> extends IterableElementBase<string, R> {
709
772
 
710
773
 
711
774
 
775
+
776
+
777
+
778
+
779
+
780
+
781
+
712
782
 
713
783
 
714
784
 
@@ -755,6 +825,13 @@ export declare class Trie<R = any> extends IterableElementBase<string, R> {
755
825
 
756
826
 
757
827
 
828
+
829
+
830
+
831
+
832
+
833
+
834
+
758
835
 
759
836
 
760
837
 
@@ -796,6 +873,13 @@ export declare class Trie<R = any> extends IterableElementBase<string, R> {
796
873
 
797
874
 
798
875
 
876
+
877
+
878
+
879
+
880
+
881
+
882
+
799
883
 
800
884
 
801
885
 
@@ -1,5 +1,5 @@
1
1
  import { BinaryTreeNode } from '../data-structures';
2
- import type { BinaryTreeDeleteResult, BinaryTreeOptions, BTNRep, DFSOrderPattern, EntryCallback, IterationType, NodeCallback, NodePredicate, OptNodeOrNull, ReduceEntryCallback, ToEntryFn } from '../types';
2
+ import type { BinaryTreeOptions, BTNRep, DFSOrderPattern, EntryCallback, IterationType, NodeCallback, NodePredicate, OptNodeOrNull, ReduceEntryCallback, ToEntryFn } from '../types';
3
3
  /**
4
4
  * Public, implementation-agnostic binary tree API.
5
5
  * K = key, V = value, R = raw/record used with toEntryFn (optional).
@@ -19,7 +19,7 @@ export interface IBinaryTree<K = any, V = any, R = any> {
19
19
  add(keyOrNodeOrEntryOrRawElement: BTNRep<K, V, BinaryTreeNode<K, V>>, value?: V, count?: number): boolean;
20
20
  set(keyOrNodeOrEntryOrRawElement: BTNRep<K, V, BinaryTreeNode<K, V>>, value?: V, count?: number): boolean;
21
21
  addMany(keysNodesEntriesOrRaws: Iterable<K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined | R>, values?: Iterable<V | undefined>): boolean[];
22
- delete(keyNodeEntryRawOrPredicate: BTNRep<K, V, BinaryTreeNode<K, V>> | NodePredicate<BinaryTreeNode<K, V> | null>): BinaryTreeDeleteResult<BinaryTreeNode<K, V>>[];
22
+ delete(keyNodeEntryRawOrPredicate: BTNRep<K, V, BinaryTreeNode<K, V>> | NodePredicate<BinaryTreeNode<K, V> | null>): boolean;
23
23
  clear(): void;
24
24
  isEmpty(): boolean;
25
25
  get(keyNodeEntryOrPredicate: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined, startNode?: K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined, iterationType?: IterationType): V | undefined;
@@ -56,5 +56,4 @@ export interface IBinaryTree<K = any, V = any, R = any> {
56
56
  filter(predicate: EntryCallback<K, V | undefined, boolean>, thisArg?: unknown): this;
57
57
  map<MK = K, MV = V, MR = any>(callback: EntryCallback<K, V | undefined, [MK, MV]>, options?: Partial<BinaryTreeOptions<MK, MV, MR>>, thisArg?: unknown): IBinaryTree<MK, MV, MR>;
58
58
  merge(anotherTree: IBinaryTree<K, V, R>): void;
59
- refill(keysNodesEntriesOrRaws: Iterable<K | BinaryTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined | R>, values?: Iterable<V | undefined>): void;
60
59
  }
@@ -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
  *
@@ -353,6 +382,13 @@ var stackTyped = (() => {
353
382
 
354
383
 
355
384
 
385
+
386
+
387
+
388
+
389
+
390
+
391
+
356
392
 
357
393
 
358
394
 
@@ -413,6 +449,13 @@ var stackTyped = (() => {
413
449
 
414
450
 
415
451
 
452
+
453
+
454
+
455
+
456
+
457
+
458
+
416
459
 
417
460
 
418
461
 
@@ -462,6 +505,13 @@ var stackTyped = (() => {
462
505
 
463
506
 
464
507
 
508
+
509
+
510
+
511
+
512
+
513
+
514
+
465
515
 
466
516
 
467
517
 
@@ -511,6 +561,13 @@ var stackTyped = (() => {
511
561
 
512
562
 
513
563
 
564
+
565
+
566
+
567
+
568
+
569
+
570
+
514
571
 
515
572
 
516
573
 
@@ -569,6 +626,13 @@ var stackTyped = (() => {
569
626
 
570
627
 
571
628
 
629
+
630
+
631
+
632
+
633
+
634
+
635
+
572
636
 
573
637
 
574
638
 
@@ -642,6 +706,13 @@ var stackTyped = (() => {
642
706
 
643
707
 
644
708
 
709
+
710
+
711
+
712
+
713
+
714
+
715
+
645
716
 
646
717
 
647
718
 
@@ -658,18 +729,18 @@ var stackTyped = (() => {
658
729
  */
659
730
  delete(element) {
660
731
  const idx = this._indexOfByEquals(element);
661
- return this.deleteAt(idx);
732
+ return this.deleteAt(idx) !== void 0;
662
733
  }
663
734
  /**
664
735
  * Delete the element at an index.
665
736
  * @remarks Time O(N), Space O(1)
666
737
  * @param index - Zero-based index from the bottom.
667
- * @returns True if removed.
738
+ * @returns The removed element, or undefined if the index is out of range.
668
739
  */
669
740
  deleteAt(index) {
670
- if (index < 0 || index >= this.elements.length) return false;
741
+ if (index < 0 || index >= this.elements.length) return void 0;
671
742
  const spliced = this.elements.splice(index, 1);
672
- return spliced.length === 1;
743
+ return spliced[0];
673
744
  }
674
745
  /**
675
746
  * Delete the first element that satisfies a predicate.
@@ -715,6 +786,13 @@ var stackTyped = (() => {
715
786
 
716
787
 
717
788
 
789
+
790
+
791
+
792
+
793
+
794
+
795
+
718
796
 
719
797
 
720
798
 
@@ -761,6 +839,13 @@ var stackTyped = (() => {
761
839
 
762
840
 
763
841
 
842
+
843
+
844
+
845
+
846
+
847
+
848
+
764
849
 
765
850
 
766
851
 
@@ -813,6 +898,13 @@ var stackTyped = (() => {
813
898
 
814
899
 
815
900
 
901
+
902
+
903
+
904
+
905
+
906
+
907
+
816
908
 
817
909
 
818
910
 
@@ -885,6 +977,13 @@ var stackTyped = (() => {
885
977
 
886
978
 
887
979
 
980
+
981
+
982
+
983
+
984
+
985
+
986
+
888
987
 
889
988
 
890
989
 
@@ -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 * @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 * @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 * @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 * @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 * @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 * @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);\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 \n \n \n \n \n \n \n \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 * @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 * @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 * @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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;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,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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AC,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:()=>f,ERR:()=>b,Range:()=>m,Stack:()=>E,raise:()=>a});function a(s,t){throw new s(t)}var b={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 f=(e=>(e[e.VISIT=0]="VISIT",e[e.PROCESS=1]="PROCESS",e))(f||{}),m=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 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 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 E=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 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}),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
  *