stack-typed 2.4.5 → 2.5.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 (76) hide show
  1. package/README.md +6 -36
  2. package/dist/cjs/index.cjs +270 -100
  3. package/dist/cjs/index.cjs.map +1 -1
  4. package/dist/cjs-legacy/index.cjs +269 -99
  5. package/dist/cjs-legacy/index.cjs.map +1 -1
  6. package/dist/esm/index.mjs +270 -100
  7. package/dist/esm/index.mjs.map +1 -1
  8. package/dist/esm-legacy/index.mjs +269 -99
  9. package/dist/esm-legacy/index.mjs.map +1 -1
  10. package/dist/types/data-structures/base/iterable-element-base.d.ts +1 -1
  11. package/dist/types/data-structures/binary-tree/avl-tree.d.ts +128 -51
  12. package/dist/types/data-structures/binary-tree/binary-indexed-tree.d.ts +210 -164
  13. package/dist/types/data-structures/binary-tree/binary-tree.d.ts +429 -78
  14. package/dist/types/data-structures/binary-tree/bst.d.ts +311 -28
  15. package/dist/types/data-structures/binary-tree/red-black-tree.d.ts +212 -32
  16. package/dist/types/data-structures/binary-tree/segment-tree.d.ts +218 -152
  17. package/dist/types/data-structures/binary-tree/tree-map.d.ts +1281 -5
  18. package/dist/types/data-structures/binary-tree/tree-multi-map.d.ts +1087 -201
  19. package/dist/types/data-structures/binary-tree/tree-multi-set.d.ts +858 -65
  20. package/dist/types/data-structures/binary-tree/tree-set.d.ts +1133 -5
  21. package/dist/types/data-structures/graph/directed-graph.d.ts +219 -47
  22. package/dist/types/data-structures/graph/map-graph.d.ts +59 -1
  23. package/dist/types/data-structures/graph/undirected-graph.d.ts +204 -59
  24. package/dist/types/data-structures/hash/hash-map.d.ts +230 -77
  25. package/dist/types/data-structures/heap/heap.d.ts +287 -99
  26. package/dist/types/data-structures/heap/max-heap.d.ts +46 -0
  27. package/dist/types/data-structures/heap/min-heap.d.ts +59 -0
  28. package/dist/types/data-structures/linked-list/doubly-linked-list.d.ts +286 -44
  29. package/dist/types/data-structures/linked-list/singly-linked-list.d.ts +278 -65
  30. package/dist/types/data-structures/linked-list/skip-linked-list.d.ts +415 -12
  31. package/dist/types/data-structures/matrix/matrix.d.ts +331 -0
  32. package/dist/types/data-structures/priority-queue/max-priority-queue.d.ts +57 -0
  33. package/dist/types/data-structures/priority-queue/min-priority-queue.d.ts +60 -0
  34. package/dist/types/data-structures/priority-queue/priority-queue.d.ts +60 -0
  35. package/dist/types/data-structures/queue/deque.d.ts +272 -65
  36. package/dist/types/data-structures/queue/queue.d.ts +211 -42
  37. package/dist/types/data-structures/stack/stack.d.ts +174 -32
  38. package/dist/types/data-structures/trie/trie.d.ts +213 -43
  39. package/dist/types/types/data-structures/binary-tree/segment-tree.d.ts +1 -1
  40. package/dist/types/types/data-structures/linked-list/skip-linked-list.d.ts +1 -4
  41. package/dist/umd/stack-typed.js +267 -97
  42. package/dist/umd/stack-typed.js.map +1 -1
  43. package/dist/umd/stack-typed.min.js +1 -1
  44. package/dist/umd/stack-typed.min.js.map +1 -1
  45. package/package.json +2 -2
  46. package/src/data-structures/base/iterable-element-base.ts +4 -5
  47. package/src/data-structures/binary-tree/avl-tree.ts +134 -51
  48. package/src/data-structures/binary-tree/binary-indexed-tree.ts +302 -247
  49. package/src/data-structures/binary-tree/binary-tree.ts +429 -79
  50. package/src/data-structures/binary-tree/bst.ts +335 -34
  51. package/src/data-structures/binary-tree/red-black-tree.ts +290 -97
  52. package/src/data-structures/binary-tree/segment-tree.ts +372 -248
  53. package/src/data-structures/binary-tree/tree-map.ts +1284 -6
  54. package/src/data-structures/binary-tree/tree-multi-map.ts +1094 -211
  55. package/src/data-structures/binary-tree/tree-multi-set.ts +858 -65
  56. package/src/data-structures/binary-tree/tree-set.ts +1136 -9
  57. package/src/data-structures/graph/directed-graph.ts +219 -47
  58. package/src/data-structures/graph/map-graph.ts +59 -1
  59. package/src/data-structures/graph/undirected-graph.ts +204 -59
  60. package/src/data-structures/hash/hash-map.ts +230 -77
  61. package/src/data-structures/heap/heap.ts +287 -99
  62. package/src/data-structures/heap/max-heap.ts +46 -0
  63. package/src/data-structures/heap/min-heap.ts +59 -0
  64. package/src/data-structures/linked-list/doubly-linked-list.ts +286 -44
  65. package/src/data-structures/linked-list/singly-linked-list.ts +278 -65
  66. package/src/data-structures/linked-list/skip-linked-list.ts +689 -90
  67. package/src/data-structures/matrix/matrix.ts +416 -12
  68. package/src/data-structures/priority-queue/max-priority-queue.ts +57 -0
  69. package/src/data-structures/priority-queue/min-priority-queue.ts +60 -0
  70. package/src/data-structures/priority-queue/priority-queue.ts +60 -0
  71. package/src/data-structures/queue/deque.ts +272 -65
  72. package/src/data-structures/queue/queue.ts +211 -42
  73. package/src/data-structures/stack/stack.ts +174 -32
  74. package/src/data-structures/trie/trie.ts +213 -43
  75. package/src/types/data-structures/binary-tree/segment-tree.ts +1 -1
  76. package/src/types/data-structures/linked-list/skip-linked-list.ts +2 -1
@@ -1,4 +1,4 @@
1
- "use strict";var stackTyped=(()=>{var c=Object.defineProperty;var f=Object.getOwnPropertyDescriptor;var d=Object.getOwnPropertyNames;var p=Object.prototype.hasOwnProperty;var R=(s,t,e)=>t in s?c(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var k=(s,t)=>{for(var e in t)c(s,e,{get:t[e],enumerable:!0})},g=(s,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of d(t))!p.call(s,r)&&r!==e&&c(s,r,{get:()=>t[r],enumerable:!(n=f(t,r))||n.enumerable});return s};var w=s=>g(c({},"__esModule",{value:!0}),s);var o=(s,t,e)=>R(s,typeof t!="symbol"?t+"":t,e);var I={};k(I,{DFSOperation:()=>b,ERR:()=>a,Range:()=>E,Stack:()=>m});var a={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}.`};var b=(e=>(e[e.VISIT=0]="VISIT",e[e.PROCESS=1]="PROCESS",e))(b||{}),E=class{constructor(t,e,n=!0,r=!0){this.low=t;this.high=e;this.includeLow=n;this.includeHigh=r}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;if(typeof e=="function")this._toElementFn=e;else if(e)throw new TypeError(a.notAFunction("toElementFn"))}}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();if(l.done)throw new TypeError(a.reduceEmpty());i=l.value,n=1}for(let l of r)i=t(i,l,n++,this);return i}toArray(){return[...this]}toVisual(){return[...this]}print(){console.log(this.toVisual())}};var m=class extends 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 w(I);})();
1
+ "use strict";var stackTyped=(()=>{var u=Object.defineProperty;var f=Object.getOwnPropertyDescriptor;var d=Object.getOwnPropertyNames;var p=Object.prototype.hasOwnProperty;var R=(s,t,e)=>t in s?u(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var k=(s,t)=>{for(var e in t)u(s,e,{get:t[e],enumerable:!0})},g=(s,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of d(t))!p.call(s,i)&&i!==e&&u(s,i,{get:()=>t[i],enumerable:!(n=f(t,i))||n.enumerable});return s};var w=s=>g(u({},"__esModule",{value:!0}),s);var o=(s,t,e)=>R(s,typeof t!="symbol"?t+"":t,e);var I={};k(I,{DFSOperation:()=>b,ERR:()=>m,Range:()=>E,Stack:()=>h});var c=class{constructor(t){o(this,"_toElementFn");if(t){let{toElementFn:e}=t;if(typeof e=="function")this._toElementFn=e;else if(e)throw new TypeError("toElementFn must be a function type")}}get toElementFn(){return this._toElementFn}*[Symbol.iterator](...t){yield*this._getIterator(...t)}*values(){for(let t of this)yield t}every(t,e){let n=0;for(let i of this)if(e===void 0){if(!t(i,n++,this))return!1}else if(!t.call(e,i,n++,this))return!1;return!0}some(t,e){let n=0;for(let i of this)if(e===void 0){if(t(i,n++,this))return!0}else if(t.call(e,i,n++,this))return!0;return!1}forEach(t,e){let n=0;for(let i of this)e===void 0?t(i,n++,this):t.call(e,i,n++,this)}find(t,e){let n=0;for(let i of this)if(e===void 0){if(t(i,n++,this))return i}else if(t.call(e,i,n++,this))return i}has(t){for(let e of this)if(e===t)return!0;return!1}reduce(t,e){let n=0,i=this[Symbol.iterator](),r;if(arguments.length>=2)r=e;else{let l=i.next();if(l.done)throw new TypeError("Reduce of empty structure with no initial value");r=l.value,n=1}for(let l of i)r=t(r,l,n++,this);return r}toArray(){return[...this]}toVisual(){return[...this]}print(){console.log(this.toVisual())}};var h=class extends c{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 i of e)this.toElementFn?n.push(this.push(this.toElementFn(i))):n.push(this.push(i));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 i=this._createInstance({toElementFn:this.toElementFn}),r=0;for(let l of this)e.call(n,l,r,this)&&i.push(l),r++;return i}mapSame(e,n){let i=this._createInstance({toElementFn:this.toElementFn}),r=0;for(let l of this){let a=n===void 0?e(l,r++,this):e.call(n,l,r++,this);i.push(a)}return i}map(e,n,i){let r=this._createLike([],{...n!=null?n:{}}),l=0;for(let a of this)r.push(i===void 0?e(a,l,this):e.call(i,a,l,this)),l++;return r}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 i=this.constructor;return new i(e,n)}*_getIterator(){for(let e=0;e<this.elements.length;e++)yield this.elements[e]}};var m={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}.`};var b=(e=>(e[e.VISIT=0]="VISIT",e[e.PROCESS=1]="PROCESS",e))(b||{}),E=class{constructor(t,e,n=!0,i=!0){this.low=t;this.high=e;this.includeLow=n;this.includeHigh=i}isInRange(t,e){let n=this.includeLow?e(t,this.low)>=0:e(t,this.low)>0,i=this.includeHigh?e(t,this.high)<=0:e(t,this.high)<0;return n&&i}};return w(I);})();
2
2
  /**
3
3
  * data-structure-typed
4
4
  *
@@ -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 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} as const;\n","export { ERR } 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 { ERR } 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) throw new TypeError(ERR.notAFunction('toElementFn'));\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 readonly _toElementFn?: (rawElement: R) => E;\n\n /**\n * Exposes the current `toElementFn`, if configured.\n *\n * @returns The converter function or `undefined` when not set.\n * @remarks\n * Time O(1), Space O(1).\n */\n get toElementFn(): ((rawElement: R) => E) | undefined {\n return this._toElementFn;\n }\n\n /**\n * Returns an iterator over the structure's elements.\n *\n * @param args Optional iterator arguments forwarded to the internal iterator.\n * @returns An `IterableIterator<E>` that yields the elements in traversal order.\n *\n * @remarks\n * Producing the iterator is O(1); consuming the entire iterator is Time O(n) with O(1) extra space.\n */\n *[Symbol.iterator](...args: unknown[]): IterableIterator<E> {\n yield* this._getIterator(...args);\n }\n\n /**\n * Returns an iterator over the values (alias of the default iterator).\n *\n * @returns An `IterableIterator<E>` over all elements.\n * @remarks\n * Creating the iterator is O(1); full iteration is Time O(n), Space O(1).\n */\n *values(): IterableIterator<E> {\n for (const item of this) yield item;\n }\n\n /**\n * Tests whether all elements satisfy the predicate.\n *\n * @template TReturn\n * @param predicate Function invoked for each element with signature `(value, index, self)`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns `true` if every element passes; otherwise `false`.\n *\n * @remarks\n * Time O(n) in the worst case; may exit early when the first failure is found. Space O(1).\n */\n every(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): boolean {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n if (!predicate(item, index++, this)) return false;\n } else {\n const fn = predicate as (this: unknown, v: E, i: number, self: this) => boolean;\n if (!fn.call(thisArg, item, index++, this)) return false;\n }\n }\n return true;\n }\n\n /**\n * Tests whether at least one element satisfies the predicate.\n *\n * @param predicate Function invoked for each element with signature `(value, index, self)`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns `true` if any element passes; otherwise `false`.\n *\n * @remarks\n * Time O(n) in the worst case; may exit early on first success. Space O(1).\n */\n some(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): boolean {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n if (predicate(item, index++, this)) return true;\n } else {\n const fn = predicate as (this: unknown, v: E, i: number, self: this) => boolean;\n if (fn.call(thisArg, item, index++, this)) return true;\n }\n }\n return false;\n }\n\n /**\n * Invokes a callback for each element in iteration order.\n *\n * @param callbackfn Function invoked per element with signature `(value, index, self)`.\n * @param thisArg Optional `this` binding for the callback.\n * @returns `void`.\n *\n * @remarks\n * Time O(n), Space O(1).\n */\n forEach(callbackfn: ElementCallback<E, R, void>, thisArg?: unknown): void {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n callbackfn(item, index++, this);\n } else {\n const fn = callbackfn as (this: unknown, v: E, i: number, self: this) => void;\n fn.call(thisArg, item, index++, this);\n }\n }\n }\n\n /**\n * Finds the first element that satisfies the predicate and returns it.\n *\n * @overload\n * Finds the first element of type `S` (a subtype of `E`) that satisfies the predicate and returns it.\n * @template S\n * @param predicate Type-guard predicate: `(value, index, self) => value is S`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns The matched element typed as `S`, or `undefined` if not found.\n *\n * @overload\n * @param predicate Boolean predicate: `(value, index, self) => boolean`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns The first matching element as `E`, or `undefined` if not found.\n *\n * @remarks\n * Time O(n) in the worst case; may exit early on the first match. Space O(1).\n */\n find<S extends E>(predicate: ElementCallback<E, R, S>, thisArg?: unknown): S | undefined;\n find(predicate: ElementCallback<E, R, unknown>, thisArg?: unknown): E | undefined;\n\n // Implementation signature\n find(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): E | undefined {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n if (predicate(item, index++, this)) return item;\n } else {\n const fn = predicate as (this: unknown, v: E, i: number, self: this) => boolean;\n if (fn.call(thisArg, item, index++, this)) return item;\n }\n }\n return;\n }\n\n /**\n * Checks whether a strictly-equal element exists in the structure.\n *\n * @param element The element to test with `===` equality.\n * @returns `true` if an equal element is found; otherwise `false`.\n *\n * @remarks\n * Time O(n) in the worst case. Space O(1).\n */\n has(element: E): boolean {\n for (const ele of this) if (ele === element) return true;\n return false;\n }\n\n reduce(callbackfn: ReduceElementCallback<E, R>): E;\n reduce(callbackfn: ReduceElementCallback<E, R>, initialValue: E): E;\n reduce<U>(callbackfn: ReduceElementCallback<E, R, U>, initialValue: U): U;\n\n /**\n * Reduces all elements to a single accumulated value.\n *\n * @overload\n * @param callbackfn Reducer of signature `(acc, value, index, self) => nextAcc`. The first element is used as the initial accumulator.\n * @returns The final accumulated value typed as `E`.\n *\n * @overload\n * @param callbackfn Reducer of signature `(acc, value, index, self) => nextAcc`.\n * @param initialValue The initial accumulator value of type `E`.\n * @returns The final accumulated value typed as `E`.\n *\n * @overload\n * @template U The accumulator type when it differs from `E`.\n * @param callbackfn Reducer of signature `(acc: U, value, index, self) => U`.\n * @param initialValue The initial accumulator value of type `U`.\n * @returns The final accumulated value typed as `U`.\n *\n * @remarks\n * Time O(n), Space O(1). Throws if called on an empty structure without `initialValue`.\n */\n reduce<U>(callbackfn: ReduceElementCallback<E, R, U>, initialValue?: U): U {\n let index = 0;\n const iter = this[Symbol.iterator]();\n let acc: U;\n\n if (arguments.length >= 2) {\n acc = initialValue as U;\n } else {\n const first = iter.next();\n if (first.done) throw new TypeError(ERR.reduceEmpty());\n acc = first.value as unknown as U;\n index = 1;\n }\n\n for (const value of iter) {\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 * // 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 * @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 * @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 */\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 get size(): number {\n return this.elements.length;\n }\n\n /**\n * Create a stack from an array of elements.\n * @remarks Time O(N), Space O(N)\n * @template E\n * @template R\n * @param this - The constructor (subclass) to instantiate.\n * @param elements - Array of elements to push in order.\n * @param [options] - Options forwarded to the constructor.\n * @returns A new Stack populated from the array.\n */\n\n static fromArray<E, R = any>(\n this: new (elements?: Iterable<E> | Iterable<R>, options?: StackOptions<E, R>) => any,\n elements: E[],\n options?: StackOptions<E, R>\n ) {\n return new this(elements, options);\n }\n\n /**\n * Check whether the stack is empty.\n * @remarks Time O(1), Space O(1)\n * @returns True if size is 0.\n */\n\n isEmpty(): boolean {\n return this.elements.length === 0;\n }\n\n /**\n * Get the top element without removing it.\n * @remarks Time O(1), Space O(1)\n * @returns Top element or undefined.\n */\n\n peek(): E | undefined {\n return this.isEmpty() ? undefined : this.elements[this.elements.length - 1];\n }\n\n /**\n * Push one element onto the top.\n * @remarks Time O(1), Space O(1)\n * @param element - Element to push.\n * @returns True when pushed.\n */\n\n push(element: E): boolean {\n this.elements.push(element);\n return true;\n }\n\n /**\n * Pop and return the top element.\n * @remarks Time O(1), Space O(1)\n * @returns Removed element or undefined.\n */\n\n pop(): E | undefined {\n return this.isEmpty() ? undefined : this.elements.pop();\n }\n\n /**\n * Push many elements from an iterable.\n * @remarks Time O(N), Space O(1)\n * @param elements - Iterable of elements (or raw records if toElementFn is set).\n * @returns Array of per-element success flags.\n */\n\n pushMany(elements: Iterable<E> | Iterable<R>): boolean[] {\n const ans: boolean[] = [];\n for (const el of elements) {\n if (this.toElementFn) ans.push(this.push(this.toElementFn(el as R)));\n else ans.push(this.push(el as E));\n }\n return ans;\n }\n\n /**\n * Delete the first occurrence of a specific element.\n * @remarks Time O(N), Space O(1)\n * @param element - Element to remove (using the configured equality).\n * @returns True if an element was removed.\n */\n\n delete(element: E): boolean {\n const idx = this._indexOfByEquals(element);\n return this.deleteAt(idx);\n }\n\n /**\n * Delete the element at an index.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index from the bottom.\n * @returns True if removed.\n */\n\n deleteAt(index: number): boolean {\n if (index < 0 || index >= this.elements.length) return false;\n const spliced = this.elements.splice(index, 1);\n return spliced.length === 1;\n }\n\n /**\n * Delete the first element that satisfies a predicate.\n * @remarks Time O(N), Space O(1)\n * @param predicate - Function (value, index, stack) → boolean to decide deletion.\n * @returns True if a match was removed.\n */\n\n deleteWhere(predicate: (value: E, index: number, stack: this) => boolean): boolean {\n for (let i = 0; i < this.elements.length; i++) {\n if (predicate(this.elements[i], i, this)) {\n this.elements.splice(i, 1);\n return true;\n }\n }\n return false;\n }\n\n /**\n * Remove all elements and reset storage.\n * @remarks Time O(1), Space O(1)\n * @returns void\n */\n\n clear(): void {\n this._elements = [];\n }\n\n /**\n * Deep clone this stack.\n * @remarks Time O(N), Space O(N)\n * @returns A new stack with the same content.\n */\n\n clone(): this {\n const out = this._createInstance({ toElementFn: this.toElementFn });\n for (const v of this) out.push(v);\n return out;\n }\n\n /**\n * Filter elements into a new stack of the same class.\n * @remarks Time O(N), Space O(N)\n * @param predicate - Predicate (value, index, stack) → boolean to keep value.\n * @param [thisArg] - Value for `this` inside the predicate.\n * @returns A new stack with kept values.\n */\n\n filter(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): this {\n const out = this._createInstance({ toElementFn: this.toElementFn });\n let index = 0;\n for (const v of this) {\n if (predicate.call(thisArg, v, index, this)) out.push(v);\n index++;\n }\n return out;\n }\n\n /**\n * Map values into a new stack of the same element type.\n * @remarks Time O(N), Space O(N)\n * @param callback - Mapping function (value, index, stack) → newValue.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new stack with mapped values.\n */\n\n mapSame(callback: ElementCallback<E, R, E>, thisArg?: unknown): this {\n const out = this._createInstance({ toElementFn: this.toElementFn });\n let index = 0;\n for (const v of this) {\n const mv = thisArg === undefined ? callback(v, index++, this) : callback.call(thisArg, v, index++, this);\n out.push(mv);\n }\n return out;\n }\n\n /**\n * Map values into a new stack (possibly different element type).\n * @remarks Time O(N), Space O(N)\n * @template EM\n * @template RM\n * @param callback - Mapping function (value, index, stack) → newElement.\n * @param [options] - Options for the output stack (e.g., toElementFn).\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new Stack with mapped elements.\n */\n\n map<EM, RM>(\n callback: ElementCallback<E, R, EM>,\n options?: IterableElementBaseOptions<EM, RM>,\n thisArg?: unknown\n ): Stack<EM, RM> {\n const out = this._createLike<EM, RM>([], { ...(options ?? {}) });\n let index = 0;\n for (const v of this) {\n out.push(thisArg === undefined ? callback(v, index, this) : callback.call(thisArg, v, index, this));\n index++;\n }\n return out;\n }\n\n /**\n * Set the equality comparator used by delete/search operations.\n * @remarks Time O(1), Space O(1)\n * @param equals - Equality predicate (a, b) → boolean.\n * @returns This stack.\n */\n\n setEquality(equals: (a: E, b: E) => boolean): this {\n this._equals = equals;\n return this;\n }\n\n /**\n * (Protected) Find the index of a target element using the equality function.\n * @remarks Time O(N), Space O(1)\n * @param target - Element to search for.\n * @returns Index or -1 if not found.\n */\n\n protected _indexOfByEquals(target: E): number {\n for (let i = 0; i < this.elements.length; i++) if (this._equals(this.elements[i], target)) return i;\n return -1;\n }\n\n /**\n * (Protected) Create an empty instance of the same concrete class.\n * @remarks Time O(1), Space O(1)\n * @param [options] - Options forwarded to the constructor.\n * @returns An empty like-kind stack instance.\n */\n\n protected _createInstance(options?: StackOptions<E, R>): this {\n const Ctor = this.constructor as new (elements?: Iterable<E> | Iterable<R>, options?: StackOptions<E, R>) => this;\n return new Ctor([], options);\n }\n\n /**\n * (Protected) Create a like-kind stack and seed it from an iterable.\n * @remarks Time O(N), Space O(N)\n * @template T\n * @template RR\n * @param [elements] - Iterable used to seed the new stack.\n * @param [options] - Options forwarded to the constructor.\n * @returns A like-kind Stack instance.\n */\n\n protected _createLike<T = E, RR = R>(\n elements: Iterable<T> | Iterable<RR> = [],\n options?: StackOptions<T, RR>\n ): Stack<T, RR> {\n const Ctor = this.constructor as new (\n elements?: Iterable<T> | Iterable<RR>,\n options?: StackOptions<T, RR>\n ) => Stack<T, RR>;\n return new Ctor(elements, options);\n }\n\n /**\n * (Protected) Iterate elements from bottom to top.\n * @remarks Time O(N), Space O(1)\n * @returns Iterator of elements.\n */\n\n protected *_getIterator(): IterableIterator<E> {\n for (let i = 0; i < this.elements.length; i++) yield this.elements[i];\n }\n}\n"],"mappings":"skBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,kBAAAE,EAAA,QAAAC,EAAA,UAAAC,EAAA,UAAAC,ICIO,IAAMC,EAAM,CAEjB,gBAAiB,CAACC,EAAeC,EAAaC,EAAaC,IACzD,GAAGA,EAAMA,EAAM,KAAO,EAAE,SAASH,CAAK,qBAAqBC,CAAG,KAAKC,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vDJ,IAEF,OAAOG,CACT,CAUA,QAAQG,EAAoCD,EAAyB,CACnE,IAAMF,EAAM,KAAK,gBAAgB,CAAE,YAAa,KAAK,WAAY,CAAC,EAC9DH,EAAQ,EACZ,QAAWI,KAAK,KAAM,CACpB,IAAMG,EAAKF,IAAY,OAAYC,EAASF,EAAGJ,IAAS,IAAI,EAAIM,EAAS,KAAKD,EAASD,EAAGJ,IAAS,IAAI,EACvGG,EAAI,KAAKI,CAAE,CACb,CACA,OAAOJ,CACT,CAaA,IACEG,EACAd,EACAa,EACe,CACf,IAAMF,EAAM,KAAK,YAAoB,CAAC,EAAG,CAAE,GAAIX,GAAA,KAAAA,EAAW,CAAC,CAAG,CAAC,EAC3DQ,EAAQ,EACZ,QAAWI,KAAK,KACdD,EAAI,KAAKE,IAAY,OAAYC,EAASF,EAAGJ,EAAO,IAAI,EAAIM,EAAS,KAAKD,EAASD,EAAGJ,EAAO,IAAI,CAAC,EAClGA,IAEF,OAAOG,CACT,CASA,YAAYK,EAAuC,CACjD,YAAK,QAAUA,EACR,IACT,CASU,iBAAiBC,EAAmB,CAC5C,QAASP,EAAI,EAAGA,EAAI,KAAK,SAAS,OAAQA,IAAK,GAAI,KAAK,QAAQ,KAAK,SAASA,CAAC,EAAGO,CAAM,EAAG,OAAOP,EAClG,MAAO,EACT,CASU,gBAAgBV,EAAoC,CAC5D,IAAMkB,EAAO,KAAK,YAClB,OAAO,IAAIA,EAAK,CAAC,EAAGlB,CAAO,CAC7B,CAYU,YACRD,EAAuC,CAAC,EACxCC,EACc,CACd,IAAMkB,EAAO,KAAK,YAIlB,OAAO,IAAIA,EAAKnB,EAAUC,CAAO,CACnC,CAQA,CAAW,cAAoC,CAC7C,QAASU,EAAI,EAAGA,EAAI,KAAK,SAAS,OAAQA,IAAK,MAAM,KAAK,SAASA,CAAC,CACtE,CACF","names":["src_exports","__export","DFSOperation","ERR","Range","Stack","ERR","index","min","max","ctx","reason","name","expected","got","op","DFSOperation","Range","low","high","includeLow","includeHigh","key","comparator","lowCheck","highCheck","IterableElementBase","options","__publicField","toElementFn","ERR","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/data-structures/base/iterable-element-base.ts","../../src/data-structures/stack/stack.ts","../../src/common/error.ts","../../src/common/index.ts"],"sourcesContent":["/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\nexport * from './data-structures/stack';\nexport * from './types/data-structures/stack';\nexport * from './types/common';\nexport * from './types/utils';\nexport * from './common';","import type { ElementCallback, IterableElementBaseOptions, ReduceElementCallback } from '../../types';\n\n/**\n * Base class that makes a data structure iterable and provides common\n * element-wise utilities (e.g., map/filter/reduce/find).\n *\n * @template E The public element type yielded by the structure.\n * @template R The underlying \"raw\" element type used internally or by converters.\n *\n * @remarks\n * This class implements the JavaScript iteration protocol (via `Symbol.iterator`)\n * and offers array-like helpers with predictable time/space complexity.\n */\nexport abstract class IterableElementBase<E, R> implements Iterable<E> {\n /**\n * Create a new iterable base.\n *\n * @param options Optional behavior overrides. When provided, a `toElementFn`\n * is used to convert a raw element (`R`) into a public element (`E`).\n *\n * @remarks\n * Time O(1), Space O(1).\n */\n protected constructor(options?: IterableElementBaseOptions<E, R>) {\n if (options) {\n const { toElementFn } = options;\n if (typeof toElementFn === 'function') this._toElementFn = toElementFn;\n else if (toElementFn) throw new TypeError('toElementFn must be a function type');\n }\n }\n\n /**\n * The converter used to transform a raw element (`R`) into a public element (`E`).\n *\n * @remarks\n * Time O(1), Space O(1).\n */\n protected _toElementFn?: (rawElement: R) => E;\n\n /**\n * Exposes the current `toElementFn`, if configured.\n *\n * @returns The converter function or `undefined` when not set.\n * @remarks\n * Time O(1), Space O(1).\n */\n get toElementFn(): ((rawElement: R) => E) | undefined {\n return this._toElementFn;\n }\n\n /**\n * Returns an iterator over the structure's elements.\n *\n * @param args Optional iterator arguments forwarded to the internal iterator.\n * @returns An `IterableIterator<E>` that yields the elements in traversal order.\n *\n * @remarks\n * Producing the iterator is O(1); consuming the entire iterator is Time O(n) with O(1) extra space.\n */\n *[Symbol.iterator](...args: unknown[]): IterableIterator<E> {\n yield* this._getIterator(...args);\n }\n\n /**\n * Returns an iterator over the values (alias of the default iterator).\n *\n * @returns An `IterableIterator<E>` over all elements.\n * @remarks\n * Creating the iterator is O(1); full iteration is Time O(n), Space O(1).\n */\n *values(): IterableIterator<E> {\n for (const item of this) yield item;\n }\n\n /**\n * Tests whether all elements satisfy the predicate.\n *\n * @template TReturn\n * @param predicate Function invoked for each element with signature `(value, index, self)`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns `true` if every element passes; otherwise `false`.\n *\n * @remarks\n * Time O(n) in the worst case; may exit early when the first failure is found. Space O(1).\n */\n every(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): boolean {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n if (!predicate(item, index++, this)) return false;\n } else {\n const fn = predicate as (this: unknown, v: E, i: number, self: this) => boolean;\n if (!fn.call(thisArg, item, index++, this)) return false;\n }\n }\n return true;\n }\n\n /**\n * Tests whether at least one element satisfies the predicate.\n *\n * @param predicate Function invoked for each element with signature `(value, index, self)`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns `true` if any element passes; otherwise `false`.\n *\n * @remarks\n * Time O(n) in the worst case; may exit early on first success. Space O(1).\n */\n some(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): boolean {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n if (predicate(item, index++, this)) return true;\n } else {\n const fn = predicate as (this: unknown, v: E, i: number, self: this) => boolean;\n if (fn.call(thisArg, item, index++, this)) return true;\n }\n }\n return false;\n }\n\n /**\n * Invokes a callback for each element in iteration order.\n *\n * @param callbackfn Function invoked per element with signature `(value, index, self)`.\n * @param thisArg Optional `this` binding for the callback.\n * @returns `void`.\n *\n * @remarks\n * Time O(n), Space O(1).\n */\n forEach(callbackfn: ElementCallback<E, R, void>, thisArg?: unknown): void {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n callbackfn(item, index++, this);\n } else {\n const fn = callbackfn as (this: unknown, v: E, i: number, self: this) => void;\n fn.call(thisArg, item, index++, this);\n }\n }\n }\n\n /**\n * Finds the first element that satisfies the predicate and returns it.\n *\n * @overload\n * Finds the first element of type `S` (a subtype of `E`) that satisfies the predicate and returns it.\n * @template S\n * @param predicate Type-guard predicate: `(value, index, self) => value is S`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns The matched element typed as `S`, or `undefined` if not found.\n *\n * @overload\n * @param predicate Boolean predicate: `(value, index, self) => boolean`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns The first matching element as `E`, or `undefined` if not found.\n *\n * @remarks\n * Time O(n) in the worst case; may exit early on the first match. Space O(1).\n */\n find<S extends E>(predicate: ElementCallback<E, R, S>, thisArg?: unknown): S | undefined;\n find(predicate: ElementCallback<E, R, unknown>, thisArg?: unknown): E | undefined;\n\n // Implementation signature\n find(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): E | undefined {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n if (predicate(item, index++, this)) return item;\n } else {\n const fn = predicate as (this: unknown, v: E, i: number, self: this) => boolean;\n if (fn.call(thisArg, item, index++, this)) return item;\n }\n }\n return;\n }\n\n /**\n * Checks whether a strictly-equal element exists in the structure.\n *\n * @param element The element to test with `===` equality.\n * @returns `true` if an equal element is found; otherwise `false`.\n *\n * @remarks\n * Time O(n) in the worst case. Space O(1).\n */\n has(element: E): boolean {\n for (const ele of this) if (ele === element) return true;\n return false;\n }\n\n reduce(callbackfn: ReduceElementCallback<E, R>): E;\n reduce(callbackfn: ReduceElementCallback<E, R>, initialValue: E): E;\n reduce<U>(callbackfn: ReduceElementCallback<E, R, U>, initialValue: U): U;\n\n /**\n * Reduces all elements to a single accumulated value.\n *\n * @overload\n * @param callbackfn Reducer of signature `(acc, value, index, self) => nextAcc`. The first element is used as the initial accumulator.\n * @returns The final accumulated value typed as `E`.\n *\n * @overload\n * @param callbackfn Reducer of signature `(acc, value, index, self) => nextAcc`.\n * @param initialValue The initial accumulator value of type `E`.\n * @returns The final accumulated value typed as `E`.\n *\n * @overload\n * @template U The accumulator type when it differs from `E`.\n * @param callbackfn Reducer of signature `(acc: U, value, index, self) => U`.\n * @param initialValue The initial accumulator value of type `U`.\n * @returns The final accumulated value typed as `U`.\n *\n * @remarks\n * Time O(n), Space O(1). Throws if called on an empty structure without `initialValue`.\n */\n reduce<U>(callbackfn: ReduceElementCallback<E, R, U>, initialValue?: U): U {\n let index = 0;\n const iter = this[Symbol.iterator]();\n let acc: U;\n\n if (arguments.length >= 2) {\n acc = initialValue as U;\n } else {\n const first = iter.next();\n if (first.done) throw new TypeError('Reduce of empty structure with no initial value');\n acc = first.value as unknown as U;\n index = 1;\n }\n\n for (const value of iter as unknown as Iterable<E>) {\n acc = callbackfn(acc, value, index++, this);\n }\n return acc;\n }\n\n /**\n * Materializes the elements into a new array.\n *\n * @returns A shallow array copy of the iteration order.\n * @remarks\n * Time O(n), Space O(n).\n */\n toArray(): E[] {\n return [...this];\n }\n\n /**\n * Returns a representation of the structure suitable for quick visualization.\n * Defaults to an array of elements; subclasses may override to provide richer visuals.\n *\n * @returns A visual representation (array by default).\n * @remarks\n * Time O(n), Space O(n).\n */\n toVisual(): E[] {\n return [...this];\n }\n\n /**\n * Prints `toVisual()` to the console. Intended for quick debugging.\n *\n * @returns `void`.\n * @remarks\n * Time O(n) due to materialization, Space O(n) for the intermediate representation.\n */\n print(): void {\n console.log(this.toVisual());\n }\n\n /**\n * Indicates whether the structure currently contains no elements.\n *\n * @returns `true` if empty; otherwise `false`.\n * @remarks\n * Expected Time O(1), Space O(1) for most implementations.\n */\n abstract isEmpty(): boolean;\n\n /**\n * Removes all elements from the structure.\n *\n * @returns `void`.\n * @remarks\n * Expected Time O(1) or O(n) depending on the implementation; Space O(1).\n */\n abstract clear(): void;\n\n /**\n * Creates a structural copy with the same element values and configuration.\n *\n * @returns A clone of the current instance (same concrete type).\n * @remarks\n * Expected Time O(n) to copy elements; Space O(n).\n */\n abstract clone(): this;\n\n /**\n * Maps each element to a new element and returns a new iterable structure.\n *\n * @template EM The mapped element type.\n * @template RM The mapped raw element type used internally by the target structure.\n * @param callback Function with signature `(value, index, self) => mapped`.\n * @param options Optional options for the returned structure, including its `toElementFn`.\n * @param thisArg Optional `this` binding for the callback.\n * @returns A new `IterableElementBase<EM, RM>` containing mapped elements.\n *\n * @remarks\n * Time O(n), Space O(n).\n */\n abstract map<EM, RM>(\n callback: ElementCallback<E, R, EM>,\n options?: IterableElementBaseOptions<EM, RM>,\n thisArg?: unknown\n ): IterableElementBase<EM, RM>;\n\n /**\n * Maps each element to the same element type and returns the same concrete structure type.\n *\n * @param callback Function with signature `(value, index, self) => mappedValue`.\n * @param thisArg Optional `this` binding for the callback.\n * @returns A new instance of the same concrete type with mapped elements.\n *\n * @remarks\n * Time O(n), Space O(n).\n */\n abstract mapSame(callback: ElementCallback<E, R, E>, thisArg?: unknown): this;\n\n /**\n * Filters elements using the provided predicate and returns the same concrete structure type.\n *\n * @param predicate Function with signature `(value, index, self) => boolean`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns A new instance of the same concrete type containing only elements that pass the predicate.\n *\n * @remarks\n * Time O(n), Space O(k) where `k` is the number of kept elements.\n */\n abstract filter(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): this;\n\n /**\n * Internal iterator factory used by the default iterator.\n *\n * @param args Optional iterator arguments.\n * @returns An iterator over elements.\n *\n * @remarks\n * Implementations should yield in O(1) per element with O(1) extra space when possible.\n */\n protected abstract _getIterator(...args: unknown[]): IterableIterator<E>;\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type { ElementCallback, IterableElementBaseOptions, StackOptions } from '../../types';\nimport { IterableElementBase } from '../base';\n\n/**\n * LIFO stack with array storage and optional record→element conversion.\n * @remarks Time O(1), Space O(1)\n * @template E\n * @template R\n * 1. Last In, First Out (LIFO): The core characteristic of a stack is its last in, first out nature, meaning the last element added to the stack will be the first to be removed.\n * 2. Uses: Stacks are commonly used for managing a series of tasks or elements that need to be processed in a last in, first out manner. They are widely used in various scenarios, such as in function calls in programming languages, evaluation of arithmetic expressions, and backtracking algorithms.\n * 3. Performance: Stack operations are typically O(1) in time complexity, meaning that regardless of the stack's size, adding, removing, and viewing the top element are very fast operations.\n * 4. Function Calls: In most modern programming languages, the records of function calls are managed through a stack. When a function is called, its record (including parameters, local variables, and return address) is 'pushed' into the stack. When the function returns, its record is 'popped' from the stack.\n * 5. Expression Evaluation: Used for the evaluation of arithmetic or logical expressions, especially when dealing with parenthesis matching and operator precedence.\n * 6. Backtracking Algorithms: In problems where multiple branches need to be explored but only one branch can be explored at a time, stacks can be used to save the state at each branching point.\n * @example\n * // 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 * @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 * @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 * @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 * @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 * @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 * @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 * @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 * @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 * @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 * @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","/**\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} as const;\n","export { ERR } 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"],"mappings":"skBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,kBAAAE,EAAA,QAAAC,EAAA,UAAAC,EAAA,UAAAC,ICaO,IAAeC,EAAf,KAAgE,CAU3D,YAAYC,EAA4C,CAclEC,EAAA,KAAU,gBAbR,GAAID,EAAS,CACX,GAAM,CAAE,YAAAE,CAAY,EAAIF,EACxB,GAAI,OAAOE,GAAgB,WAAY,KAAK,aAAeA,UAClDA,EAAa,MAAM,IAAI,UAAU,qCAAqC,CACjF,CACF,CAiBA,IAAI,aAAkD,CACpD,OAAO,KAAK,YACd,CAWA,EAAE,OAAO,QAAQ,KAAKC,EAAsC,CAC1D,MAAO,KAAK,aAAa,GAAGA,CAAI,CAClC,CASA,CAAC,QAA8B,CAC7B,QAAWC,KAAQ,KAAM,MAAMA,CACjC,CAaA,MAAMC,EAA2CC,EAA4B,CAC3E,IAAIC,EAAQ,EACZ,QAAWH,KAAQ,KACjB,GAAIE,IAAY,QACd,GAAI,CAACD,EAAUD,EAAMG,IAAS,IAAI,EAAG,MAAO,WAGxC,CADOF,EACH,KAAKC,EAASF,EAAMG,IAAS,IAAI,EAAG,MAAO,GAGvD,MAAO,EACT,CAYA,KAAKF,EAA2CC,EAA4B,CAC1E,IAAIC,EAAQ,EACZ,QAAWH,KAAQ,KACjB,GAAIE,IAAY,QACd,GAAID,EAAUD,EAAMG,IAAS,IAAI,EAAG,MAAO,WAEhCF,EACJ,KAAKC,EAASF,EAAMG,IAAS,IAAI,EAAG,MAAO,GAGtD,MAAO,EACT,CAYA,QAAQC,EAAyCF,EAAyB,CACxE,IAAIC,EAAQ,EACZ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C,EACAC,EACAC,EAAsB,GACtBC,EAAuB,GAC9B,CAJO,SAAAH,EACA,UAAAC,EACA,gBAAAC,EACA,iBAAAC,CAIT,CAGA,UAAUC,EAAQC,EAA6C,CAC7D,IAAMC,EAAW,KAAK,WAAaD,EAAWD,EAAK,KAAK,GAAG,GAAK,EAAIC,EAAWD,EAAK,KAAK,GAAG,EAAI,EAC1FG,EAAY,KAAK,YAAcF,EAAWD,EAAK,KAAK,IAAI,GAAK,EAAIC,EAAWD,EAAK,KAAK,IAAI,EAAI,EACpG,OAAOE,GAAYC,CACrB,CACF","names":["src_exports","__export","DFSOperation","ERR","Range","Stack","IterableElementBase","options","__publicField","toElementFn","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","ERR","index","min","max","ctx","reason","name","expected","got","op","DFSOperation","Range","low","high","includeLow","includeHigh","key","comparator","lowCheck","highCheck"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "stack-typed",
3
- "version": "2.4.5",
3
+ "version": "2.5.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.4.5"
106
+ "data-structure-typed": "^2.5.0"
107
107
  }
108
108
  }
@@ -1,5 +1,4 @@
1
1
  import type { ElementCallback, IterableElementBaseOptions, ReduceElementCallback } from '../../types';
2
- import { ERR } from '../../common';
3
2
 
4
3
  /**
5
4
  * Base class that makes a data structure iterable and provides common
@@ -26,7 +25,7 @@ export abstract class IterableElementBase<E, R> implements Iterable<E> {
26
25
  if (options) {
27
26
  const { toElementFn } = options;
28
27
  if (typeof toElementFn === 'function') this._toElementFn = toElementFn;
29
- else if (toElementFn) throw new TypeError(ERR.notAFunction('toElementFn'));
28
+ else if (toElementFn) throw new TypeError('toElementFn must be a function type');
30
29
  }
31
30
  }
32
31
 
@@ -36,7 +35,7 @@ export abstract class IterableElementBase<E, R> implements Iterable<E> {
36
35
  * @remarks
37
36
  * Time O(1), Space O(1).
38
37
  */
39
- protected readonly _toElementFn?: (rawElement: R) => E;
38
+ protected _toElementFn?: (rawElement: R) => E;
40
39
 
41
40
  /**
42
41
  * Exposes the current `toElementFn`, if configured.
@@ -225,12 +224,12 @@ export abstract class IterableElementBase<E, R> implements Iterable<E> {
225
224
  acc = initialValue as U;
226
225
  } else {
227
226
  const first = iter.next();
228
- if (first.done) throw new TypeError(ERR.reduceEmpty());
227
+ if (first.done) throw new TypeError('Reduce of empty structure with no initial value');
229
228
  acc = first.value as unknown as U;
230
229
  index = 1;
231
230
  }
232
231
 
233
- for (const value of iter) {
232
+ for (const value of iter as unknown as Iterable<E>) {
234
233
  acc = callbackfn(acc, value, index++, this);
235
234
  }
236
235
  return acc;
@@ -123,16 +123,12 @@ export class AVLTreeNode<K = any, V = any> {
123
123
  *
124
124
  * @returns The node's color.
125
125
  */
126
+ /* istanbul ignore next -- inherited field, used by RedBlackTree subclass */ /* istanbul ignore next -- inherited field, not used by AVLTree */
126
127
  get color(): RBTNColor {
127
128
  return this._color;
128
129
  }
129
130
 
130
- /**
131
- * Sets the color of the node.
132
- * @remarks Time O(1), Space O(1)
133
- *
134
- * @param value - The new color.
135
- */
131
+ /* istanbul ignore next -- inherited field, not used by AVLTree */
136
132
  set color(value: RBTNColor) {
137
133
  this._color = value;
138
134
  }
@@ -145,16 +141,12 @@ export class AVLTreeNode<K = any, V = any> {
145
141
  *
146
142
  * @returns The subtree node count.
147
143
  */
144
+ /* istanbul ignore next -- inherited field, not used by AVLTree */
148
145
  get count(): number {
149
146
  return this._count;
150
147
  }
151
148
 
152
- /**
153
- * Sets the count of nodes in the subtree.
154
- * @remarks Time O(1), Space O(1)
155
- *
156
- * @param value - The new count.
157
- */
149
+ /* istanbul ignore next -- inherited field, not used by AVLTree */
158
150
  set count(value: number) {
159
151
  this._count = value;
160
152
  }
@@ -176,6 +168,7 @@ export class AVLTreeNode<K = any, V = any> {
176
168
  return this.left || this.right ? 'ROOT_RIGHT' : 'RIGHT';
177
169
  }
178
170
 
171
+ /* istanbul ignore next -- defensive: unreachable if tree structure is correct */
179
172
  return 'MAL_NODE';
180
173
  }
181
174
  }
@@ -197,28 +190,6 @@ export class AVLTreeNode<K = any, V = any> {
197
190
  * 7. Path Length: The path length from the root to any leaf is longer compared to an unbalanced BST, but shorter than a linear chain of nodes.
198
191
  *
199
192
  * @example
200
- * // basic AVLTree creation and add operation
201
- * // Create a simple AVLTree with initial values
202
- * const tree = new AVLTree([5, 2, 8, 1, 9]);
203
- *
204
- * tree.print();
205
- * // _2___
206
- * // / \
207
- * // 1 _8_
208
- * // / \
209
- * // 5 9
210
- *
211
- * // Verify the tree maintains sorted order
212
- * console.log([...tree.keys()]); // [1, 2, 5, 8, 9];
213
- *
214
- * // Check size
215
- * console.log(tree.size); // 5;
216
- *
217
- * // Add a new element
218
- * tree.set(3);
219
- * console.log(tree.size); // 6;
220
- * console.log([...tree.keys()]); // [1, 2, 3, 5, 8, 9];
221
- * @example
222
193
  * // AVLTree has and get operations
223
194
  * const tree = new AVLTree<number>([11, 3, 15, 1, 8, 13, 16, 2, 6, 9, 12, 14, 4, 7, 10, 5]);
224
195
  *
@@ -233,23 +204,6 @@ export class AVLTreeNode<K = any, V = any> {
233
204
  * // Verify tree is balanced
234
205
  * console.log(tree.isAVLBalanced()); // true;
235
206
  * @example
236
- * // AVLTree delete and balance verification
237
- * const tree = new AVLTree([11, 3, 15, 1, 8, 13, 16, 2, 6, 9, 12, 14, 4, 7, 10, 5]);
238
- *
239
- * // Delete an element
240
- * tree.delete(10);
241
- * console.log(tree.has(10)); // false;
242
- *
243
- * // Tree should remain balanced after deletion
244
- * console.log(tree.isAVLBalanced()); // true;
245
- *
246
- * // Size decreased
247
- * console.log(tree.size); // 15;
248
- *
249
- * // Remaining elements are still sorted
250
- * const keys = [...tree.keys()];
251
- * console.log(keys); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16];
252
- * @example
253
207
  * // AVLTree for university ranking system with strict balance
254
208
  * interface University {
255
209
  * name: string;
@@ -406,6 +360,48 @@ export class AVLTree<K = any, V = any, R = any> extends BST<K, V, R> implements
406
360
  * @param keyNodeOrEntry - The key, node, or entry to set.
407
361
  * @param [value] - The value, if providing just a key.
408
362
  * @returns True if the addition was successful, false otherwise.
363
+
364
+
365
+
366
+
367
+
368
+
369
+
370
+
371
+
372
+
373
+
374
+
375
+
376
+
377
+
378
+
379
+
380
+
381
+
382
+
383
+
384
+
385
+
386
+
387
+
388
+
389
+
390
+
391
+
392
+
393
+
394
+
395
+
396
+
397
+
398
+
399
+ * @example
400
+ * // Set a key-value pair
401
+ * const avl = new AVLTree<number, string>();
402
+ * avl.set(1, 'one');
403
+ * avl.set(2, 'two');
404
+ * console.log(avl.get(1)); // 'one';
409
405
  */
410
406
  override set(
411
407
  keyNodeOrEntry: K | AVLTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined,
@@ -424,6 +420,45 @@ export class AVLTree<K = any, V = any, R = any> extends BST<K, V, R> implements
424
420
  *
425
421
  * @param keyNodeOrEntry - The node to delete.
426
422
  * @returns An array containing deletion results.
423
+
424
+
425
+
426
+
427
+
428
+
429
+
430
+
431
+
432
+
433
+
434
+
435
+
436
+
437
+
438
+
439
+
440
+
441
+
442
+
443
+
444
+
445
+
446
+
447
+
448
+
449
+
450
+
451
+
452
+
453
+
454
+
455
+
456
+ * @example
457
+ * // Remove nodes and verify structure
458
+ * const avl = new AVLTree<number>([5, 3, 7, 1, 4, 6, 8]);
459
+ * avl.delete(3);
460
+ * console.log(avl.has(3)); // false;
461
+ * console.log(avl.size); // 6;
427
462
  */
428
463
  override delete(
429
464
  keyNodeOrEntry: K | AVLTreeNode<K, V> | [K | null | undefined, V | undefined] | null | undefined
@@ -445,6 +480,26 @@ export class AVLTree<K = any, V = any, R = any> extends BST<K, V, R> implements
445
480
  *
446
481
  * @param [iterationType=this.iterationType] - The traversal method for the initial node export.
447
482
  * @returns True if successful, false if the tree was empty.
483
+
484
+
485
+
486
+
487
+
488
+
489
+
490
+
491
+
492
+
493
+
494
+
495
+ * @example
496
+ * // Rebalance the tree
497
+ * const avl = new AVLTree<number>();
498
+ * // Insert in sorted order (worst case for BST)
499
+ * for (let i = 1; i <= 7; i++) avl.add(i);
500
+ * console.log(avl.isAVLBalanced()); // false;
501
+ * avl.perfectlyBalance();
502
+ * console.log(avl.isAVLBalanced()); // true;
448
503
  */
449
504
  override perfectlyBalance(iterationType: IterationType = this.iterationType): boolean {
450
505
  const nodes = this.dfs(node => node, 'IN', false, this._root, iterationType);
@@ -486,6 +541,33 @@ export class AVLTree<K = any, V = any, R = any> extends BST<K, V, R> implements
486
541
  * @param [options] - Options for the new AVLTree.
487
542
  * @param [thisArg] - `this` context for the callback.
488
543
  * @returns A new, mapped AVLTree.
544
+
545
+
546
+
547
+
548
+
549
+
550
+
551
+
552
+
553
+
554
+
555
+
556
+
557
+
558
+
559
+
560
+
561
+
562
+
563
+
564
+
565
+
566
+ * @example
567
+ * // Transform to new tree
568
+ * const avl = new AVLTree<number, number>([[1, 10], [2, 20], [3, 30]]);
569
+ * const doubled = avl.map((value, key) => [key, (value ?? 0) * 2] as [number, number]);
570
+ * console.log([...doubled.values()]); // [20, 40, 60];
489
571
  */
490
572
  override map<MK = K, MV = V, MR = any>(
491
573
  callback: EntryCallback<K, V | undefined, [MK, MV]>,
@@ -574,6 +656,7 @@ export class AVLTree<K = any, V = any, R = any> extends BST<K, V, R> implements
574
656
 
575
657
  return destNodeEnsured;
576
658
  }
659
+ /* istanbul ignore next -- defensive: srcNode/destNode are always valid when called internally */
577
660
  return undefined;
578
661
  }
579
662