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
@@ -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":"skBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,kBAAAE,EAAA,QAAAC,EAAA,UAAAC,EAAA,UAAAC,EAAA,UAAAC,ICOO,SAASC,EACdC,EACAC,EACO,CACP,MAAM,IAAID,EAAWC,CAAO,CAC9B,CAMO,IAAMC,EAAM,CAEjB,gBAAiB,CAACC,EAA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S,OAAQA,IAAK,MAAM,KAAK,SAASA,CAAC,CACtE,CACF","names":["src_exports","__export","DFSOperation","ERR","Range","Stack","raise","raise","ErrorClass","message","ERR","index","min","max","ctx","reason","name","expected","got","op","method","DFSOperation","Range","low","high","includeLow","includeHigh","key","comparator","lowCheck","highCheck","IterableElementBase","options","__publicField","toElementFn","raise","args","item","predicate","thisArg","index","callbackfn","element","ele","initialValue","iter","acc","first","value","Stack","IterableElementBase","elements","options","__publicField","a","b","element","ans","el","idx","index","predicate","i","out","v","thisArg","callback","mv","equals","target","Ctor"]}
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":"skBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,kBAAAE,EAAA,QAAAC,EAAA,UAAAC,EAAA,UAAAC,EAAA,UAAAC,ICOO,SAASC,EACdC,EACAC,EACO,CACP,MAAM,IAAID,EAAWC,CAAO,CAC9B,CAMO,IAAMC,EAAM,CAEjB,gBAAiB,CAACC,EAAeC,EAAaC,EAAaC,IACzD,GAAGA,EAAMA,EAAM,KAAO,EAAE,SAASH,CAAK,qBAAqBC,CAAG,KAAKC,CAAG,KAExE,aAAeC,GACb,GAAGA,EAAMA,EAAM,KAAO,EAAE,4BAG1B,gBAAiB,CAACC,EAAgBD,IAChC,GAAGA,EAAMA,EAAM,KAAO,EAAE,GAAGC,CAAM,GAEnC,mBAAqBD,GACnB,GAAGA,EAAMA,EAAM,KAAO,EAAE,kEAE1B,WAAY,CAACC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ERR","Range","Stack","raise","raise","ErrorClass","message","ERR","index","min","max","ctx","reason","name","expected","got","op","method","DFSOperation","Range","low","high","includeLow","includeHigh","key","comparator","lowCheck","highCheck","IterableElementBase","options","__publicField","toElementFn","raise","args","item","predicate","thisArg","index","callbackfn","element","ele","value","_","initialValue","iter","acc","first","Stack","IterableElementBase","elements","options","__publicField","a","b","element","ans","el","idx","index","predicate","i","out","v","thisArg","callback","mv","equals","target","Ctor"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "stack-typed",
3
- "version": "2.5.3",
3
+ "version": "2.6.0",
4
4
  "description": "Stack",
5
5
  "browser": "dist/umd/stack-typed.min.js",
6
6
  "umd:main": "dist/umd/stack-typed.min.js",
@@ -103,6 +103,6 @@
103
103
  "typescript": "^4.9.5"
104
104
  },
105
105
  "dependencies": {
106
- "data-structure-typed": "^2.5.3"
106
+ "data-structure-typed": "^2.6.0"
107
107
  }
108
108
  }
@@ -191,6 +191,38 @@ export abstract class IterableElementBase<E, R> implements Iterable<E> {
191
191
  return false;
192
192
  }
193
193
 
194
+ /**
195
+ * Check whether a value exists (Array-compatible alias for `has`).
196
+ * @remarks Provided for familiarity when migrating from Array. Time O(n), Space O(1).
197
+ * @param element - Element to search for (uses `===`).
198
+ * @returns `true` if found.
199
+ */
200
+ includes(element: E): boolean {
201
+ return this.has(element);
202
+ }
203
+
204
+ /**
205
+ * Return an iterator of `[index, value]` pairs (Array-compatible).
206
+ * @remarks Provided for familiarity when migrating from Array. Time O(n), Space O(1) per step.
207
+ */
208
+ *entries(): IterableIterator<[number, E]> {
209
+ let index = 0;
210
+ for (const value of this) {
211
+ yield [index++, value];
212
+ }
213
+ }
214
+
215
+ /**
216
+ * Return an iterator of numeric indices (Array-compatible).
217
+ * @remarks Provided for familiarity when migrating from Array. Time O(n), Space O(1) per step.
218
+ */
219
+ *keys(): IterableIterator<number> {
220
+ let index = 0;
221
+ for (const _ of this) {
222
+ yield index++;
223
+ }
224
+ }
225
+
194
226
  reduce(callbackfn: ReduceElementCallback<E, R>): E;
195
227
  reduce(callbackfn: ReduceElementCallback<E, R>, initialValue: E): E;
196
228
  reduce<U>(callbackfn: ReduceElementCallback<E, R, U>, initialValue: U): U;
@@ -327,6 +327,17 @@ export abstract class LinearBase<
327
327
  */
328
328
  abstract reverse(): this;
329
329
 
330
+ /**
331
+ * Return a new instance of the same type with elements in reverse order (non-mutating).
332
+ * @remarks Provided for familiarity when migrating from Array (ES2023 `toReversed`). Time O(n), Space O(n).
333
+ * @returns A new reversed instance.
334
+ */
335
+ toReversed(): this {
336
+ const cloned = this.clone();
337
+ cloned.reverse();
338
+ return cloned as this;
339
+ }
340
+
330
341
  /**
331
342
  * Append one element or node to the tail.
332
343
  * @param elementOrNode - Element or node.
@@ -494,6 +494,18 @@ export class AVLTree<K = any, V = any, R = any> extends BST<K, V, R> implements
494
494
 
495
495
 
496
496
 
497
+
498
+
499
+
500
+
501
+
502
+
503
+
504
+
505
+
506
+
507
+
508
+
497
509
 
498
510
 
499
511
 
@@ -638,6 +650,15 @@ export class AVLTree<K = any, V = any, R = any> extends BST<K, V, R> implements
638
650
 
639
651
 
640
652
 
653
+
654
+
655
+
656
+
657
+
658
+
659
+
660
+
661
+
641
662
 
642
663
 
643
664
 
@@ -736,6 +757,12 @@ export class AVLTree<K = any, V = any, R = any> extends BST<K, V, R> implements
736
757
 
737
758
 
738
759
 
760
+
761
+
762
+
763
+
764
+
765
+
739
766
 
740
767
 
741
768
 
@@ -888,6 +915,15 @@ export class AVLTree<K = any, V = any, R = any> extends BST<K, V, R> implements
888
915
 
889
916
 
890
917
 
918
+
919
+
920
+
921
+
922
+
923
+
924
+
925
+
926
+
891
927
 
892
928
 
893
929
 
@@ -119,6 +119,12 @@ export class BinaryIndexedTree implements Iterable<number> {
119
119
 
120
120
 
121
121
 
122
+
123
+
124
+
125
+
126
+
127
+
122
128
 
123
129
 
124
130
 
@@ -204,6 +210,12 @@ export class BinaryIndexedTree implements Iterable<number> {
204
210
 
205
211
 
206
212
 
213
+
214
+
215
+
216
+
217
+
218
+
207
219
 
208
220
 
209
221
 
@@ -289,6 +301,12 @@ export class BinaryIndexedTree implements Iterable<number> {
289
301
 
290
302
 
291
303
 
304
+
305
+
306
+
307
+
308
+
309
+
292
310
 
293
311
 
294
312
 
@@ -374,6 +392,12 @@ export class BinaryIndexedTree implements Iterable<number> {
374
392
 
375
393
 
376
394
 
395
+
396
+
397
+
398
+
399
+
400
+
377
401
 
378
402
 
379
403
 
@@ -457,6 +481,12 @@ export class BinaryIndexedTree implements Iterable<number> {
457
481
 
458
482
 
459
483
 
484
+
485
+
486
+
487
+
488
+
489
+
460
490
 
461
491
 
462
492
 
@@ -548,6 +578,12 @@ export class BinaryIndexedTree implements Iterable<number> {
548
578
 
549
579
 
550
580
 
581
+
582
+
583
+
584
+
585
+
586
+
551
587
 
552
588
 
553
589
 
@@ -608,6 +644,9 @@ export class BinaryIndexedTree implements Iterable<number> {
608
644
 
609
645
 
610
646
 
647
+
648
+
649
+
611
650
 
612
651
 
613
652
 
@@ -681,6 +720,9 @@ export class BinaryIndexedTree implements Iterable<number> {
681
720
 
682
721
 
683
722
 
723
+
724
+
725
+
684
726
 
685
727
 
686
728
 
@@ -596,6 +596,9 @@ export class BinaryTree<K = any, V = any, R = any>
596
596
 
597
597
 
598
598
 
599
+
600
+
601
+
599
602
 
600
603
 
601
604
 
@@ -657,6 +660,9 @@ export class BinaryTree<K = any, V = any, R = any>
657
660
 
658
661
 
659
662
 
663
+
664
+
665
+
660
666
 
661
667
 
662
668
 
@@ -780,6 +786,9 @@ export class BinaryTree<K = any, V = any, R = any>
780
786
 
781
787
 
782
788
 
789
+
790
+
791
+
783
792
 
784
793
 
785
794
 
@@ -831,6 +840,9 @@ export class BinaryTree<K = any, V = any, R = any>
831
840
 
832
841
 
833
842
 
843
+
844
+
845
+
834
846
 
835
847
 
836
848
 
@@ -908,6 +920,9 @@ export class BinaryTree<K = any, V = any, R = any>
908
920
 
909
921
 
910
922
 
923
+
924
+
925
+
911
926
 
912
927
 
913
928
 
@@ -1025,6 +1040,9 @@ export class BinaryTree<K = any, V = any, R = any>
1025
1040
 
1026
1041
 
1027
1042
 
1043
+
1044
+
1045
+
1028
1046
 
1029
1047
 
1030
1048
 
@@ -1070,6 +1088,9 @@ export class BinaryTree<K = any, V = any, R = any>
1070
1088
 
1071
1089
 
1072
1090
 
1091
+
1092
+
1093
+
1073
1094
 
1074
1095
 
1075
1096
 
@@ -1210,6 +1231,9 @@ export class BinaryTree<K = any, V = any, R = any>
1210
1231
 
1211
1232
 
1212
1233
 
1234
+
1235
+
1236
+
1213
1237
 
1214
1238
 
1215
1239
 
@@ -1289,6 +1313,9 @@ export class BinaryTree<K = any, V = any, R = any>
1289
1313
 
1290
1314
 
1291
1315
 
1316
+
1317
+
1318
+
1292
1319
 
1293
1320
 
1294
1321
 
@@ -1362,6 +1389,9 @@ export class BinaryTree<K = any, V = any, R = any>
1362
1389
 
1363
1390
 
1364
1391
 
1392
+
1393
+
1394
+
1365
1395
 
1366
1396
 
1367
1397
 
@@ -1428,6 +1458,9 @@ export class BinaryTree<K = any, V = any, R = any>
1428
1458
 
1429
1459
 
1430
1460
 
1461
+
1462
+
1463
+
1431
1464
 
1432
1465
 
1433
1466
 
@@ -1530,6 +1563,9 @@ export class BinaryTree<K = any, V = any, R = any>
1530
1563
 
1531
1564
 
1532
1565
 
1566
+
1567
+
1568
+
1533
1569
 
1534
1570
 
1535
1571
 
@@ -1583,6 +1619,9 @@ export class BinaryTree<K = any, V = any, R = any>
1583
1619
 
1584
1620
 
1585
1621
 
1622
+
1623
+
1624
+
1586
1625
 
1587
1626
 
1588
1627
 
@@ -1648,6 +1687,9 @@ export class BinaryTree<K = any, V = any, R = any>
1648
1687
 
1649
1688
 
1650
1689
 
1690
+
1691
+
1692
+
1651
1693
 
1652
1694
 
1653
1695
 
@@ -1743,6 +1785,9 @@ export class BinaryTree<K = any, V = any, R = any>
1743
1785
 
1744
1786
 
1745
1787
 
1788
+
1789
+
1790
+
1746
1791
 
1747
1792
 
1748
1793
 
@@ -1812,6 +1857,9 @@ export class BinaryTree<K = any, V = any, R = any>
1812
1857
 
1813
1858
 
1814
1859
 
1860
+
1861
+
1862
+
1815
1863
 
1816
1864
 
1817
1865
 
@@ -2122,6 +2170,9 @@ export class BinaryTree<K = any, V = any, R = any>
2122
2170
 
2123
2171
 
2124
2172
 
2173
+
2174
+
2175
+
2125
2176
 
2126
2177
 
2127
2178
 
@@ -2214,6 +2265,9 @@ export class BinaryTree<K = any, V = any, R = any>
2214
2265
 
2215
2266
 
2216
2267
 
2268
+
2269
+
2270
+
2217
2271
 
2218
2272
 
2219
2273
 
@@ -2365,6 +2419,9 @@ export class BinaryTree<K = any, V = any, R = any>
2365
2419
 
2366
2420
 
2367
2421
 
2422
+
2423
+
2424
+
2368
2425
 
2369
2426
 
2370
2427
 
@@ -2469,6 +2526,9 @@ export class BinaryTree<K = any, V = any, R = any>
2469
2526
 
2470
2527
 
2471
2528
 
2529
+
2530
+
2531
+
2472
2532
 
2473
2533
 
2474
2534
 
@@ -2591,6 +2651,9 @@ export class BinaryTree<K = any, V = any, R = any>
2591
2651
 
2592
2652
 
2593
2653
 
2654
+
2655
+
2656
+
2594
2657
 
2595
2658
 
2596
2659
 
@@ -2757,6 +2820,9 @@ export class BinaryTree<K = any, V = any, R = any>
2757
2820
 
2758
2821
 
2759
2822
 
2823
+
2824
+
2825
+
2760
2826
 
2761
2827
 
2762
2828
 
@@ -2814,6 +2880,9 @@ export class BinaryTree<K = any, V = any, R = any>
2814
2880
 
2815
2881
 
2816
2882
 
2883
+
2884
+
2885
+
2817
2886
 
2818
2887
 
2819
2888
 
@@ -2875,6 +2944,9 @@ export class BinaryTree<K = any, V = any, R = any>
2875
2944
 
2876
2945
 
2877
2946
 
2947
+
2948
+
2949
+
2878
2950
 
2879
2951
 
2880
2952
 
@@ -2969,6 +3041,9 @@ export class BinaryTree<K = any, V = any, R = any>
2969
3041
 
2970
3042
 
2971
3043
 
3044
+
3045
+
3046
+
2972
3047
 
2973
3048
 
2974
3049