data-structure-typed 2.4.5 → 2.5.1

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 (240) hide show
  1. package/.vitepress/cache/deps_temp_51f5f1b0/chunk-7OIKW5WK.js +12984 -0
  2. package/.vitepress/cache/deps_temp_51f5f1b0/package.json +3 -0
  3. package/.vitepress/cache/deps_temp_51f5f1b0/vitepress___@vue_devtools-api.js +4505 -0
  4. package/.vitepress/cache/deps_temp_51f5f1b0/vitepress___@vueuse_core.js +9731 -0
  5. package/.vitepress/cache/deps_temp_51f5f1b0/vue.js +347 -0
  6. package/CHANGELOG.md +3 -1
  7. package/README.md +78 -31
  8. package/dist/cjs/binary-tree.cjs +23698 -0
  9. package/dist/cjs/graph.cjs +5236 -0
  10. package/dist/cjs/hash.cjs +1262 -0
  11. package/dist/cjs/heap.cjs +1540 -0
  12. package/dist/cjs/index.cjs +24509 -2899
  13. package/dist/cjs/linked-list.cjs +4370 -0
  14. package/dist/cjs/matrix.cjs +1042 -0
  15. package/dist/cjs/priority-queue.cjs +1314 -0
  16. package/dist/cjs/queue.cjs +4090 -0
  17. package/dist/cjs/stack.cjs +861 -0
  18. package/dist/cjs/trie.cjs +1173 -0
  19. package/dist/cjs-legacy/binary-tree.cjs +23730 -0
  20. package/dist/cjs-legacy/graph.cjs +5234 -0
  21. package/dist/cjs-legacy/hash.cjs +1262 -0
  22. package/dist/cjs-legacy/heap.cjs +1537 -0
  23. package/dist/cjs-legacy/index.cjs +32555 -10936
  24. package/dist/cjs-legacy/linked-list.cjs +4376 -0
  25. package/dist/cjs-legacy/matrix.cjs +1045 -0
  26. package/dist/cjs-legacy/priority-queue.cjs +1312 -0
  27. package/dist/cjs-legacy/queue.cjs +4088 -0
  28. package/dist/cjs-legacy/stack.cjs +861 -0
  29. package/dist/cjs-legacy/trie.cjs +1172 -0
  30. package/dist/esm/binary-tree.mjs +23683 -0
  31. package/dist/esm/graph.mjs +5223 -0
  32. package/dist/esm/hash.mjs +1259 -0
  33. package/dist/esm/heap.mjs +1534 -0
  34. package/dist/esm/index.mjs +24507 -2898
  35. package/dist/esm/linked-list.mjs +4363 -0
  36. package/dist/esm/matrix.mjs +1038 -0
  37. package/dist/esm/priority-queue.mjs +1310 -0
  38. package/dist/esm/queue.mjs +4086 -0
  39. package/dist/esm/stack.mjs +859 -0
  40. package/dist/esm/trie.mjs +1170 -0
  41. package/dist/esm-legacy/binary-tree.mjs +23715 -0
  42. package/dist/esm-legacy/graph.mjs +5221 -0
  43. package/dist/esm-legacy/hash.mjs +1259 -0
  44. package/dist/esm-legacy/heap.mjs +1531 -0
  45. package/dist/esm-legacy/index.mjs +32553 -10935
  46. package/dist/esm-legacy/linked-list.mjs +4369 -0
  47. package/dist/esm-legacy/matrix.mjs +1041 -0
  48. package/dist/esm-legacy/priority-queue.mjs +1308 -0
  49. package/dist/esm-legacy/queue.mjs +4084 -0
  50. package/dist/esm-legacy/stack.mjs +859 -0
  51. package/dist/esm-legacy/trie.mjs +1169 -0
  52. package/dist/types/data-structures/base/index.d.ts +1 -0
  53. package/dist/types/data-structures/base/iterable-element-base.d.ts +1 -1
  54. package/dist/types/data-structures/base/iterable-entry-base.d.ts +8 -8
  55. package/dist/types/data-structures/base/linear-base.d.ts +3 -3
  56. package/dist/types/data-structures/binary-tree/avl-tree.d.ts +368 -51
  57. package/dist/types/data-structures/binary-tree/binary-indexed-tree.d.ts +473 -147
  58. package/dist/types/data-structures/binary-tree/binary-tree.d.ts +931 -80
  59. package/dist/types/data-structures/binary-tree/bst.d.ts +792 -29
  60. package/dist/types/data-structures/binary-tree/red-black-tree.d.ts +592 -32
  61. package/dist/types/data-structures/binary-tree/segment-tree.d.ts +320 -135
  62. package/dist/types/data-structures/binary-tree/tree-map.d.ts +3662 -6
  63. package/dist/types/data-structures/binary-tree/tree-multi-map.d.ts +3487 -201
  64. package/dist/types/data-structures/binary-tree/tree-multi-set.d.ts +2778 -65
  65. package/dist/types/data-structures/binary-tree/tree-set.d.ts +3414 -6
  66. package/dist/types/data-structures/graph/abstract-graph.d.ts +4 -4
  67. package/dist/types/data-structures/graph/directed-graph.d.ts +419 -47
  68. package/dist/types/data-structures/graph/map-graph.d.ts +59 -1
  69. package/dist/types/data-structures/graph/undirected-graph.d.ts +384 -59
  70. package/dist/types/data-structures/hash/hash-map.d.ts +462 -89
  71. package/dist/types/data-structures/heap/heap.d.ts +567 -99
  72. package/dist/types/data-structures/heap/max-heap.d.ts +46 -0
  73. package/dist/types/data-structures/heap/min-heap.d.ts +59 -0
  74. package/dist/types/data-structures/linked-list/doubly-linked-list.d.ts +631 -49
  75. package/dist/types/data-structures/linked-list/singly-linked-list.d.ts +581 -68
  76. package/dist/types/data-structures/linked-list/skip-linked-list.d.ts +775 -12
  77. package/dist/types/data-structures/matrix/matrix.d.ts +491 -0
  78. package/dist/types/data-structures/priority-queue/max-priority-queue.d.ts +57 -0
  79. package/dist/types/data-structures/priority-queue/min-priority-queue.d.ts +60 -0
  80. package/dist/types/data-structures/priority-queue/priority-queue.d.ts +60 -0
  81. package/dist/types/data-structures/queue/deque.d.ts +578 -71
  82. package/dist/types/data-structures/queue/queue.d.ts +451 -42
  83. package/dist/types/data-structures/stack/stack.d.ts +374 -32
  84. package/dist/types/data-structures/trie/trie.d.ts +458 -48
  85. package/dist/types/interfaces/graph.d.ts +1 -1
  86. package/dist/types/types/common.d.ts +2 -2
  87. package/dist/types/types/data-structures/binary-tree/segment-tree.d.ts +1 -1
  88. package/dist/types/types/data-structures/heap/heap.d.ts +1 -0
  89. package/dist/types/types/data-structures/linked-list/skip-linked-list.d.ts +1 -4
  90. package/dist/types/types/data-structures/priority-queue/priority-queue.d.ts +1 -0
  91. package/dist/types/types/utils/validate-type.d.ts +4 -4
  92. package/dist/umd/data-structure-typed.js +32432 -10808
  93. package/dist/umd/data-structure-typed.min.js +10 -4
  94. package/docs-site-docusaurus/README.md +41 -0
  95. package/docs-site-docusaurus/docs/api/README.md +52 -0
  96. package/docs-site-docusaurus/docs/api/classes/AVLTree.md +6130 -0
  97. package/docs-site-docusaurus/docs/api/classes/AVLTreeNode.md +282 -0
  98. package/docs-site-docusaurus/docs/api/classes/AbstractGraph.md +2266 -0
  99. package/docs-site-docusaurus/docs/api/classes/BST.md +5831 -0
  100. package/docs-site-docusaurus/docs/api/classes/BSTNode.md +333 -0
  101. package/docs-site-docusaurus/docs/api/classes/BinaryIndexedTree.md +455 -0
  102. package/docs-site-docusaurus/docs/api/classes/BinaryTree.md +4647 -0
  103. package/docs-site-docusaurus/docs/api/classes/BinaryTreeNode.md +331 -0
  104. package/docs-site-docusaurus/docs/api/classes/Deque.md +2767 -0
  105. package/docs-site-docusaurus/docs/api/classes/DirectedGraph.md +2999 -0
  106. package/docs-site-docusaurus/docs/api/classes/DoublyLinkedList.md +2685 -0
  107. package/docs-site-docusaurus/docs/api/classes/DoublyLinkedListNode.md +221 -0
  108. package/docs-site-docusaurus/docs/api/classes/FibonacciHeap.md +253 -0
  109. package/docs-site-docusaurus/docs/api/classes/FibonacciHeapNode.md +21 -0
  110. package/docs-site-docusaurus/docs/api/classes/HashMap.md +1333 -0
  111. package/docs-site-docusaurus/docs/api/classes/Heap.md +1881 -0
  112. package/docs-site-docusaurus/docs/api/classes/IterableElementBase.md +800 -0
  113. package/docs-site-docusaurus/docs/api/classes/IterableEntryBase.md +644 -0
  114. package/docs-site-docusaurus/docs/api/classes/LinearBase.md +1632 -0
  115. package/docs-site-docusaurus/docs/api/classes/LinearLinkedBase.md +1853 -0
  116. package/docs-site-docusaurus/docs/api/classes/LinkedHashMap.md +1108 -0
  117. package/docs-site-docusaurus/docs/api/classes/LinkedListNode.md +156 -0
  118. package/docs-site-docusaurus/docs/api/classes/LinkedListQueue.md +2824 -0
  119. package/docs-site-docusaurus/docs/api/classes/MapGraph.md +2929 -0
  120. package/docs-site-docusaurus/docs/api/classes/Matrix.md +1026 -0
  121. package/docs-site-docusaurus/docs/api/classes/MaxHeap.md +1866 -0
  122. package/docs-site-docusaurus/docs/api/classes/MaxPriorityQueue.md +1883 -0
  123. package/docs-site-docusaurus/docs/api/classes/MinHeap.md +1879 -0
  124. package/docs-site-docusaurus/docs/api/classes/MinPriorityQueue.md +1882 -0
  125. package/docs-site-docusaurus/docs/api/classes/Navigator.md +109 -0
  126. package/docs-site-docusaurus/docs/api/classes/PriorityQueue.md +1839 -0
  127. package/docs-site-docusaurus/docs/api/classes/Queue.md +2244 -0
  128. package/docs-site-docusaurus/docs/api/classes/RedBlackTree.md +6374 -0
  129. package/docs-site-docusaurus/docs/api/classes/SegmentTree.md +372 -0
  130. package/docs-site-docusaurus/docs/api/classes/SinglyLinkedList.md +2897 -0
  131. package/docs-site-docusaurus/docs/api/classes/SinglyLinkedListNode.md +169 -0
  132. package/docs-site-docusaurus/docs/api/classes/SkipList.md +1229 -0
  133. package/docs-site-docusaurus/docs/api/classes/Stack.md +1573 -0
  134. package/docs-site-docusaurus/docs/api/classes/TreeMap.md +1257 -0
  135. package/docs-site-docusaurus/docs/api/classes/TreeMultiMap.md +1475 -0
  136. package/docs-site-docusaurus/docs/api/classes/TreeSet.md +1117 -0
  137. package/docs-site-docusaurus/docs/api/classes/Trie.md +1708 -0
  138. package/docs-site-docusaurus/docs/api/classes/TrieNode.md +199 -0
  139. package/docs-site-docusaurus/docs/api/classes/UndirectedGraph.md +2979 -0
  140. package/docs-site-docusaurus/docs/guide/_category_.json +6 -0
  141. package/docs-site-docusaurus/docs/guide/architecture.md +613 -0
  142. package/docs-site-docusaurus/docs/guide/concepts.md +420 -0
  143. package/docs-site-docusaurus/docs/guide/guides.md +611 -0
  144. package/docs-site-docusaurus/docs/guide/installation.md +60 -0
  145. package/docs-site-docusaurus/docs/guide/integrations.md +823 -0
  146. package/docs-site-docusaurus/docs/guide/overview.md +638 -0
  147. package/docs-site-docusaurus/docs/guide/performance.md +833 -0
  148. package/docs-site-docusaurus/docs/guide/quick-start.md +73 -0
  149. package/docs-site-docusaurus/docusaurus.config.ts +159 -0
  150. package/docs-site-docusaurus/fix-mdx-generics.mjs +75 -0
  151. package/docs-site-docusaurus/package-lock.json +18667 -0
  152. package/docs-site-docusaurus/package.json +50 -0
  153. package/docs-site-docusaurus/prefix-class-to-methods.mjs +48 -0
  154. package/docs-site-docusaurus/sidebars.ts +23 -0
  155. package/docs-site-docusaurus/sort-protected.mjs +87 -0
  156. package/docs-site-docusaurus/src/css/custom.css +96 -0
  157. package/docs-site-docusaurus/src/pages/index.module.css +13 -0
  158. package/docs-site-docusaurus/src/pages/index.tsx +71 -0
  159. package/docs-site-docusaurus/src/pages/markdown-page.md +7 -0
  160. package/docs-site-docusaurus/src/theme/TOCItems/index.tsx +34 -0
  161. package/docs-site-docusaurus/static/.nojekyll +0 -0
  162. package/docs-site-docusaurus/static/img/docusaurus-social-card.jpg +0 -0
  163. package/docs-site-docusaurus/static/img/docusaurus.png +0 -0
  164. package/docs-site-docusaurus/static/img/favicon.ico +0 -0
  165. package/docs-site-docusaurus/static/img/favicon.png +0 -0
  166. package/docs-site-docusaurus/static/img/logo-180.png +0 -0
  167. package/docs-site-docusaurus/static/img/logo.jpg +0 -0
  168. package/docs-site-docusaurus/static/img/logo.png +0 -0
  169. package/docs-site-docusaurus/static/img/logo.svg +1 -0
  170. package/docs-site-docusaurus/static/img/og-image.png +0 -0
  171. package/docs-site-docusaurus/static/img/undraw_docusaurus_mountain.svg +171 -0
  172. package/docs-site-docusaurus/static/img/undraw_docusaurus_react.svg +170 -0
  173. package/docs-site-docusaurus/static/img/undraw_docusaurus_tree.svg +40 -0
  174. package/docs-site-docusaurus/static/robots.txt +4 -0
  175. package/docs-site-docusaurus/typedoc.json +23 -0
  176. package/package.json +109 -12
  177. package/src/data-structures/base/index.ts +1 -0
  178. package/src/data-structures/base/iterable-element-base.ts +4 -5
  179. package/src/data-structures/base/iterable-entry-base.ts +8 -8
  180. package/src/data-structures/base/linear-base.ts +3 -3
  181. package/src/data-structures/binary-tree/avl-tree.ts +386 -51
  182. package/src/data-structures/binary-tree/binary-indexed-tree.ts +596 -247
  183. package/src/data-structures/binary-tree/binary-tree.ts +956 -81
  184. package/src/data-structures/binary-tree/bst.ts +840 -35
  185. package/src/data-structures/binary-tree/red-black-tree.ts +689 -97
  186. package/src/data-structures/binary-tree/segment-tree.ts +498 -249
  187. package/src/data-structures/binary-tree/tree-map.ts +3784 -7
  188. package/src/data-structures/binary-tree/tree-multi-map.ts +3614 -211
  189. package/src/data-structures/binary-tree/tree-multi-set.ts +2874 -65
  190. package/src/data-structures/binary-tree/tree-set.ts +3531 -10
  191. package/src/data-structures/graph/abstract-graph.ts +4 -4
  192. package/src/data-structures/graph/directed-graph.ts +429 -47
  193. package/src/data-structures/graph/map-graph.ts +59 -1
  194. package/src/data-structures/graph/undirected-graph.ts +393 -59
  195. package/src/data-structures/hash/hash-map.ts +476 -92
  196. package/src/data-structures/heap/heap.ts +581 -99
  197. package/src/data-structures/heap/max-heap.ts +46 -0
  198. package/src/data-structures/heap/min-heap.ts +59 -0
  199. package/src/data-structures/linked-list/doubly-linked-list.ts +646 -47
  200. package/src/data-structures/linked-list/singly-linked-list.ts +596 -68
  201. package/src/data-structures/linked-list/skip-linked-list.ts +1067 -90
  202. package/src/data-structures/matrix/matrix.ts +584 -12
  203. package/src/data-structures/priority-queue/max-priority-queue.ts +57 -0
  204. package/src/data-structures/priority-queue/min-priority-queue.ts +60 -0
  205. package/src/data-structures/priority-queue/priority-queue.ts +60 -0
  206. package/src/data-structures/queue/deque.ts +592 -70
  207. package/src/data-structures/queue/queue.ts +463 -42
  208. package/src/data-structures/stack/stack.ts +384 -32
  209. package/src/data-structures/trie/trie.ts +470 -48
  210. package/src/interfaces/graph.ts +1 -1
  211. package/src/types/common.ts +2 -2
  212. package/src/types/data-structures/binary-tree/segment-tree.ts +1 -1
  213. package/src/types/data-structures/heap/heap.ts +1 -0
  214. package/src/types/data-structures/linked-list/skip-linked-list.ts +2 -1
  215. package/src/types/data-structures/priority-queue/priority-queue.ts +1 -0
  216. package/src/types/utils/validate-type.ts +4 -4
  217. package/vercel.json +6 -0
  218. package/dist/leetcode/avl-tree-counter.mjs +0 -2957
  219. package/dist/leetcode/avl-tree-multi-map.mjs +0 -2889
  220. package/dist/leetcode/avl-tree.mjs +0 -2720
  221. package/dist/leetcode/binary-tree.mjs +0 -1594
  222. package/dist/leetcode/bst.mjs +0 -2398
  223. package/dist/leetcode/deque.mjs +0 -683
  224. package/dist/leetcode/directed-graph.mjs +0 -1733
  225. package/dist/leetcode/doubly-linked-list.mjs +0 -709
  226. package/dist/leetcode/hash-map.mjs +0 -493
  227. package/dist/leetcode/heap.mjs +0 -542
  228. package/dist/leetcode/max-heap.mjs +0 -375
  229. package/dist/leetcode/max-priority-queue.mjs +0 -383
  230. package/dist/leetcode/min-heap.mjs +0 -363
  231. package/dist/leetcode/min-priority-queue.mjs +0 -371
  232. package/dist/leetcode/priority-queue.mjs +0 -363
  233. package/dist/leetcode/queue.mjs +0 -943
  234. package/dist/leetcode/red-black-tree.mjs +0 -2765
  235. package/dist/leetcode/singly-linked-list.mjs +0 -754
  236. package/dist/leetcode/stack.mjs +0 -217
  237. package/dist/leetcode/tree-counter.mjs +0 -3039
  238. package/dist/leetcode/tree-multi-map.mjs +0 -2913
  239. package/dist/leetcode/trie.mjs +0 -413
  240. package/dist/leetcode/undirected-graph.mjs +0 -1650
@@ -0,0 +1,1540 @@
1
+ 'use strict';
2
+
3
+ var __defProp = Object.defineProperty;
4
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
5
+
6
+ // src/data-structures/base/iterable-element-base.ts
7
+ var IterableElementBase = class {
8
+ static {
9
+ __name(this, "IterableElementBase");
10
+ }
11
+ /**
12
+ * Create a new iterable base.
13
+ *
14
+ * @param options Optional behavior overrides. When provided, a `toElementFn`
15
+ * is used to convert a raw element (`R`) into a public element (`E`).
16
+ *
17
+ * @remarks
18
+ * Time O(1), Space O(1).
19
+ */
20
+ constructor(options) {
21
+ if (options) {
22
+ const { toElementFn } = options;
23
+ if (typeof toElementFn === "function") this._toElementFn = toElementFn;
24
+ else if (toElementFn) throw new TypeError("toElementFn must be a function type");
25
+ }
26
+ }
27
+ /**
28
+ * The converter used to transform a raw element (`R`) into a public element (`E`).
29
+ *
30
+ * @remarks
31
+ * Time O(1), Space O(1).
32
+ */
33
+ _toElementFn;
34
+ /**
35
+ * Exposes the current `toElementFn`, if configured.
36
+ *
37
+ * @returns The converter function or `undefined` when not set.
38
+ * @remarks
39
+ * Time O(1), Space O(1).
40
+ */
41
+ get toElementFn() {
42
+ return this._toElementFn;
43
+ }
44
+ /**
45
+ * Returns an iterator over the structure's elements.
46
+ *
47
+ * @param args Optional iterator arguments forwarded to the internal iterator.
48
+ * @returns An `IterableIterator<E>` that yields the elements in traversal order.
49
+ *
50
+ * @remarks
51
+ * Producing the iterator is O(1); consuming the entire iterator is Time O(n) with O(1) extra space.
52
+ */
53
+ *[Symbol.iterator](...args) {
54
+ yield* this._getIterator(...args);
55
+ }
56
+ /**
57
+ * Returns an iterator over the values (alias of the default iterator).
58
+ *
59
+ * @returns An `IterableIterator<E>` over all elements.
60
+ * @remarks
61
+ * Creating the iterator is O(1); full iteration is Time O(n), Space O(1).
62
+ */
63
+ *values() {
64
+ for (const item of this) yield item;
65
+ }
66
+ /**
67
+ * Tests whether all elements satisfy the predicate.
68
+ *
69
+ * @template TReturn
70
+ * @param predicate Function invoked for each element with signature `(value, index, self)`.
71
+ * @param thisArg Optional `this` binding for the predicate.
72
+ * @returns `true` if every element passes; otherwise `false`.
73
+ *
74
+ * @remarks
75
+ * Time O(n) in the worst case; may exit early when the first failure is found. Space O(1).
76
+ */
77
+ every(predicate, thisArg) {
78
+ let index = 0;
79
+ for (const item of this) {
80
+ if (thisArg === void 0) {
81
+ if (!predicate(item, index++, this)) return false;
82
+ } else {
83
+ const fn = predicate;
84
+ if (!fn.call(thisArg, item, index++, this)) return false;
85
+ }
86
+ }
87
+ return true;
88
+ }
89
+ /**
90
+ * Tests whether at least one element satisfies the predicate.
91
+ *
92
+ * @param predicate Function invoked for each element with signature `(value, index, self)`.
93
+ * @param thisArg Optional `this` binding for the predicate.
94
+ * @returns `true` if any element passes; otherwise `false`.
95
+ *
96
+ * @remarks
97
+ * Time O(n) in the worst case; may exit early on first success. Space O(1).
98
+ */
99
+ some(predicate, thisArg) {
100
+ let index = 0;
101
+ for (const item of this) {
102
+ if (thisArg === void 0) {
103
+ if (predicate(item, index++, this)) return true;
104
+ } else {
105
+ const fn = predicate;
106
+ if (fn.call(thisArg, item, index++, this)) return true;
107
+ }
108
+ }
109
+ return false;
110
+ }
111
+ /**
112
+ * Invokes a callback for each element in iteration order.
113
+ *
114
+ * @param callbackfn Function invoked per element with signature `(value, index, self)`.
115
+ * @param thisArg Optional `this` binding for the callback.
116
+ * @returns `void`.
117
+ *
118
+ * @remarks
119
+ * Time O(n), Space O(1).
120
+ */
121
+ forEach(callbackfn, thisArg) {
122
+ let index = 0;
123
+ for (const item of this) {
124
+ if (thisArg === void 0) {
125
+ callbackfn(item, index++, this);
126
+ } else {
127
+ const fn = callbackfn;
128
+ fn.call(thisArg, item, index++, this);
129
+ }
130
+ }
131
+ }
132
+ // Implementation signature
133
+ find(predicate, thisArg) {
134
+ let index = 0;
135
+ for (const item of this) {
136
+ if (thisArg === void 0) {
137
+ if (predicate(item, index++, this)) return item;
138
+ } else {
139
+ const fn = predicate;
140
+ if (fn.call(thisArg, item, index++, this)) return item;
141
+ }
142
+ }
143
+ return;
144
+ }
145
+ /**
146
+ * Checks whether a strictly-equal element exists in the structure.
147
+ *
148
+ * @param element The element to test with `===` equality.
149
+ * @returns `true` if an equal element is found; otherwise `false`.
150
+ *
151
+ * @remarks
152
+ * Time O(n) in the worst case. Space O(1).
153
+ */
154
+ has(element) {
155
+ for (const ele of this) if (ele === element) return true;
156
+ return false;
157
+ }
158
+ /**
159
+ * Reduces all elements to a single accumulated value.
160
+ *
161
+ * @overload
162
+ * @param callbackfn Reducer of signature `(acc, value, index, self) => nextAcc`. The first element is used as the initial accumulator.
163
+ * @returns The final accumulated value typed as `E`.
164
+ *
165
+ * @overload
166
+ * @param callbackfn Reducer of signature `(acc, value, index, self) => nextAcc`.
167
+ * @param initialValue The initial accumulator value of type `E`.
168
+ * @returns The final accumulated value typed as `E`.
169
+ *
170
+ * @overload
171
+ * @template U The accumulator type when it differs from `E`.
172
+ * @param callbackfn Reducer of signature `(acc: U, value, index, self) => U`.
173
+ * @param initialValue The initial accumulator value of type `U`.
174
+ * @returns The final accumulated value typed as `U`.
175
+ *
176
+ * @remarks
177
+ * Time O(n), Space O(1). Throws if called on an empty structure without `initialValue`.
178
+ */
179
+ reduce(callbackfn, initialValue) {
180
+ let index = 0;
181
+ const iter = this[Symbol.iterator]();
182
+ let acc;
183
+ if (arguments.length >= 2) {
184
+ acc = initialValue;
185
+ } else {
186
+ const first = iter.next();
187
+ if (first.done) throw new TypeError("Reduce of empty structure with no initial value");
188
+ acc = first.value;
189
+ index = 1;
190
+ }
191
+ for (const value of iter) {
192
+ acc = callbackfn(acc, value, index++, this);
193
+ }
194
+ return acc;
195
+ }
196
+ /**
197
+ * Materializes the elements into a new array.
198
+ *
199
+ * @returns A shallow array copy of the iteration order.
200
+ * @remarks
201
+ * Time O(n), Space O(n).
202
+ */
203
+ toArray() {
204
+ return [...this];
205
+ }
206
+ /**
207
+ * Returns a representation of the structure suitable for quick visualization.
208
+ * Defaults to an array of elements; subclasses may override to provide richer visuals.
209
+ *
210
+ * @returns A visual representation (array by default).
211
+ * @remarks
212
+ * Time O(n), Space O(n).
213
+ */
214
+ toVisual() {
215
+ return [...this];
216
+ }
217
+ /**
218
+ * Prints `toVisual()` to the console. Intended for quick debugging.
219
+ *
220
+ * @returns `void`.
221
+ * @remarks
222
+ * Time O(n) due to materialization, Space O(n) for the intermediate representation.
223
+ */
224
+ print() {
225
+ console.log(this.toVisual());
226
+ }
227
+ };
228
+
229
+ // src/common/error.ts
230
+ var ERR = {
231
+ // Range / index
232
+ indexOutOfRange: /* @__PURE__ */ __name((index, min, max, ctx) => `${ctx ? ctx + ": " : ""}Index ${index} is out of range [${min}, ${max}].`, "indexOutOfRange"),
233
+ invalidIndex: /* @__PURE__ */ __name((ctx) => `${ctx ? ctx + ": " : ""}Index must be an integer.`, "invalidIndex"),
234
+ // Type / argument
235
+ invalidArgument: /* @__PURE__ */ __name((reason, ctx) => `${ctx ? ctx + ": " : ""}${reason}`, "invalidArgument"),
236
+ comparatorRequired: /* @__PURE__ */ __name((ctx) => `${ctx ? ctx + ": " : ""}Comparator is required for non-number/non-string/non-Date keys.`, "comparatorRequired"),
237
+ invalidKey: /* @__PURE__ */ __name((reason, ctx) => `${ctx ? ctx + ": " : ""}${reason}`, "invalidKey"),
238
+ notAFunction: /* @__PURE__ */ __name((name, ctx) => `${ctx ? ctx + ": " : ""}${name} must be a function.`, "notAFunction"),
239
+ invalidEntry: /* @__PURE__ */ __name((ctx) => `${ctx ? ctx + ": " : ""}Each entry must be a [key, value] tuple.`, "invalidEntry"),
240
+ invalidNaN: /* @__PURE__ */ __name((ctx) => `${ctx ? ctx + ": " : ""}NaN is not a valid key.`, "invalidNaN"),
241
+ invalidDate: /* @__PURE__ */ __name((ctx) => `${ctx ? ctx + ": " : ""}Invalid Date key.`, "invalidDate"),
242
+ reduceEmpty: /* @__PURE__ */ __name((ctx) => `${ctx ? ctx + ": " : ""}Reduce of empty structure with no initial value.`, "reduceEmpty"),
243
+ callbackReturnType: /* @__PURE__ */ __name((expected, got, ctx) => `${ctx ? ctx + ": " : ""}Callback must return ${expected}; got ${got}.`, "callbackReturnType"),
244
+ // State / operation
245
+ invalidOperation: /* @__PURE__ */ __name((reason, ctx) => `${ctx ? ctx + ": " : ""}${reason}`, "invalidOperation"),
246
+ // Matrix
247
+ matrixDimensionMismatch: /* @__PURE__ */ __name((op) => `Matrix: Dimensions must be compatible for ${op}.`, "matrixDimensionMismatch"),
248
+ matrixSingular: /* @__PURE__ */ __name(() => "Matrix: Singular matrix, inverse does not exist.", "matrixSingular"),
249
+ matrixNotSquare: /* @__PURE__ */ __name(() => "Matrix: Must be square for inversion.", "matrixNotSquare"),
250
+ matrixNotRectangular: /* @__PURE__ */ __name(() => "Matrix: Must be rectangular for transposition.", "matrixNotRectangular"),
251
+ matrixRowMismatch: /* @__PURE__ */ __name((expected, got) => `Matrix: Expected row length ${expected}, but got ${got}.`, "matrixRowMismatch")
252
+ };
253
+
254
+ // src/data-structures/heap/heap.ts
255
+ var Heap = class _Heap extends IterableElementBase {
256
+ static {
257
+ __name(this, "Heap");
258
+ }
259
+ _equals = Object.is;
260
+ /**
261
+ * Create a Heap and optionally bulk-insert elements.
262
+ * @remarks Time O(N), Space O(N)
263
+ * @param [elements] - Iterable of elements (or raw values if toElementFn is set).
264
+ * @param [options] - Options such as comparator and toElementFn.
265
+ * @returns New Heap instance.
266
+ */
267
+ constructor(elements = [], options) {
268
+ super(options);
269
+ if (options) {
270
+ const { comparator } = options;
271
+ if (comparator) this._comparator = comparator;
272
+ }
273
+ this.addMany(elements);
274
+ }
275
+ _elements = [];
276
+ /**
277
+ * Get the backing array of the heap.
278
+ * @remarks Time O(1), Space O(1)
279
+ * @returns Internal elements array.
280
+ */
281
+ get elements() {
282
+ return this._elements;
283
+ }
284
+ /**
285
+ * Get the number of elements.
286
+ * @remarks Time O(1), Space O(1)
287
+ * @returns Heap size.
288
+
289
+
290
+
291
+
292
+
293
+
294
+
295
+
296
+
297
+
298
+
299
+
300
+
301
+
302
+
303
+
304
+
305
+
306
+
307
+
308
+
309
+
310
+
311
+
312
+
313
+
314
+
315
+
316
+
317
+
318
+
319
+ * @example
320
+ * // Track heap capacity
321
+ * const heap = new Heap<number>();
322
+ * console.log(heap.size); // 0;
323
+ * heap.add(10);
324
+ * heap.add(20);
325
+ * console.log(heap.size); // 2;
326
+ * heap.poll();
327
+ * console.log(heap.size); // 1;
328
+ */
329
+ get size() {
330
+ return this.elements.length;
331
+ }
332
+ /**
333
+ * Get the last leaf element.
334
+ * @remarks Time O(1), Space O(1)
335
+ * @returns Last element or undefined.
336
+ */
337
+ get leaf() {
338
+ return this.elements[this.size - 1] ?? void 0;
339
+ }
340
+ /**
341
+ * Create a heap of the same class from an iterable.
342
+ * @remarks Time O(N), Space O(N)
343
+ * @template T
344
+ * @template R
345
+ * @template S
346
+ * @param [elements] - Iterable of elements or raw records.
347
+ * @param [options] - Heap options including comparator.
348
+ * @returns A new heap instance of this class.
349
+ */
350
+ static from(elements, options) {
351
+ return new this(elements, options);
352
+ }
353
+ /**
354
+ * Build a Heap from an iterable in linear time given a comparator.
355
+ * @remarks Time O(N), Space O(N)
356
+ * @template EE
357
+ * @template RR
358
+ * @param elements - Iterable of elements.
359
+ * @param options - Heap options including comparator.
360
+ * @returns A new Heap built from elements.
361
+ */
362
+ static heapify(elements, options) {
363
+ return new _Heap(elements, options);
364
+ }
365
+ /**
366
+ * Insert an element.
367
+ * @remarks Time O(1) amortized, Space O(1)
368
+ * @param element - Element to insert.
369
+ * @returns True.
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
+
400
+
401
+ * @example
402
+ * // basic Heap creation and add operation
403
+ * // Create a min heap (default)
404
+ * const minHeap = new Heap([5, 3, 7, 1, 9, 2]);
405
+ *
406
+ * // Verify size
407
+ * console.log(minHeap.size); // 6;
408
+ *
409
+ * // Add new element
410
+ * minHeap.add(4);
411
+ * console.log(minHeap.size); // 7;
412
+ *
413
+ * // Min heap property: smallest element at root
414
+ * const min = minHeap.peek();
415
+ * console.log(min); // 1;
416
+ */
417
+ add(element) {
418
+ this._elements.push(element);
419
+ return this._bubbleUp(this.elements.length - 1);
420
+ }
421
+ /**
422
+ * Insert many elements from an iterable.
423
+ * @remarks Time O(N log N), Space O(1)
424
+ * @param elements - Iterable of elements or raw values.
425
+ * @returns Array of per-element success flags.
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
+ * @example
455
+ * // Add multiple elements
456
+ * const heap = new Heap<number>([], { comparator: (a, b) => a - b });
457
+ * heap.addMany([5, 3, 7, 1]);
458
+ * console.log(heap.peek()); // 1;
459
+ * console.log(heap.size); // 4;
460
+ */
461
+ addMany(elements) {
462
+ const flags = [];
463
+ for (const el of elements) {
464
+ if (this.toElementFn) {
465
+ const ok = this.add(this.toElementFn(el));
466
+ flags.push(ok);
467
+ } else {
468
+ const ok = this.add(el);
469
+ flags.push(ok);
470
+ }
471
+ }
472
+ return flags;
473
+ }
474
+ /**
475
+ * Remove and return the top element.
476
+ * @remarks Time O(log N), Space O(1)
477
+ * @returns Top element or undefined.
478
+
479
+
480
+
481
+
482
+
483
+
484
+
485
+
486
+
487
+
488
+
489
+
490
+
491
+
492
+
493
+
494
+
495
+
496
+
497
+
498
+
499
+
500
+
501
+
502
+
503
+
504
+
505
+
506
+
507
+
508
+
509
+ * @example
510
+ * // Heap with custom comparator (MaxHeap behavior)
511
+ * interface Task {
512
+ * id: number;
513
+ * priority: number;
514
+ * name: string;
515
+ * }
516
+ *
517
+ * // Custom comparator for max heap behavior (higher priority first)
518
+ * const tasks: Task[] = [
519
+ * { id: 1, priority: 5, name: 'Email' },
520
+ * { id: 2, priority: 3, name: 'Chat' },
521
+ * { id: 3, priority: 8, name: 'Alert' }
522
+ * ];
523
+ *
524
+ * const maxHeap = new Heap(tasks, {
525
+ * comparator: (a: Task, b: Task) => b.priority - a.priority
526
+ * });
527
+ *
528
+ * console.log(maxHeap.size); // 3;
529
+ *
530
+ * // Peek returns highest priority task
531
+ * const topTask = maxHeap.peek();
532
+ * console.log(topTask?.priority); // 8;
533
+ * console.log(topTask?.name); // 'Alert';
534
+ */
535
+ poll() {
536
+ if (this.elements.length === 0) return;
537
+ const value = this.elements[0];
538
+ const last = this.elements.pop();
539
+ if (this.elements.length) {
540
+ this.elements[0] = last;
541
+ this._sinkDown(0, this.elements.length >> 1);
542
+ }
543
+ return value;
544
+ }
545
+ /**
546
+ * Get the current top element without removing it.
547
+ * @remarks Time O(1), Space O(1)
548
+ * @returns Top element or undefined.
549
+
550
+
551
+
552
+
553
+
554
+
555
+
556
+
557
+
558
+
559
+
560
+
561
+
562
+
563
+
564
+
565
+
566
+
567
+
568
+
569
+
570
+
571
+
572
+
573
+
574
+
575
+
576
+
577
+
578
+
579
+
580
+ * @example
581
+ * // Heap for event processing with priority
582
+ * interface Event {
583
+ * id: number;
584
+ * type: 'critical' | 'warning' | 'info';
585
+ * timestamp: number;
586
+ * message: string;
587
+ * }
588
+ *
589
+ * // Custom priority: critical > warning > info
590
+ * const priorityMap = { critical: 3, warning: 2, info: 1 };
591
+ *
592
+ * const eventHeap = new Heap<Event>([], {
593
+ * comparator: (a: Event, b: Event) => {
594
+ * const priorityA = priorityMap[a.type];
595
+ * const priorityB = priorityMap[b.type];
596
+ * return priorityB - priorityA; // Higher priority first
597
+ * }
598
+ * });
599
+ *
600
+ * // Add events in random order
601
+ * eventHeap.add({ id: 1, type: 'info', timestamp: 100, message: 'User logged in' });
602
+ * eventHeap.add({ id: 2, type: 'critical', timestamp: 101, message: 'Server down' });
603
+ * eventHeap.add({ id: 3, type: 'warning', timestamp: 102, message: 'High memory' });
604
+ * eventHeap.add({ id: 4, type: 'info', timestamp: 103, message: 'Cache cleared' });
605
+ * eventHeap.add({ id: 5, type: 'critical', timestamp: 104, message: 'Database error' });
606
+ *
607
+ * console.log(eventHeap.size); // 5;
608
+ *
609
+ * // Process events by priority (critical first)
610
+ * const processedOrder: Event[] = [];
611
+ * while (eventHeap.size > 0) {
612
+ * const event = eventHeap.poll();
613
+ * if (event) {
614
+ * processedOrder.push(event);
615
+ * }
616
+ * }
617
+ *
618
+ * // Verify critical events came first
619
+ * console.log(processedOrder[0].type); // 'critical';
620
+ * console.log(processedOrder[1].type); // 'critical';
621
+ * console.log(processedOrder[2].type); // 'warning';
622
+ * console.log(processedOrder[3].type); // 'info';
623
+ * console.log(processedOrder[4].type); // 'info';
624
+ *
625
+ * // Verify O(log n) operations
626
+ * const newHeap = new Heap<number>([5, 3, 7, 1]);
627
+ *
628
+ * // Add - O(log n)
629
+ * newHeap.add(2);
630
+ * console.log(newHeap.size); // 5;
631
+ *
632
+ * // Poll - O(log n)
633
+ * const removed = newHeap.poll();
634
+ * console.log(removed); // 1;
635
+ *
636
+ * // Peek - O(1)
637
+ * const top = newHeap.peek();
638
+ * console.log(top); // 2;
639
+ */
640
+ peek() {
641
+ return this.elements[0];
642
+ }
643
+ /**
644
+ * Check whether the heap is empty.
645
+ * @remarks Time O(1), Space O(1)
646
+ * @returns True if size is 0.
647
+
648
+
649
+
650
+
651
+
652
+
653
+
654
+
655
+
656
+
657
+
658
+
659
+
660
+
661
+
662
+
663
+
664
+
665
+
666
+
667
+
668
+
669
+
670
+
671
+
672
+
673
+
674
+
675
+
676
+ * @example
677
+ * // Check if heap is empty
678
+ * const heap = new Heap<number>([], { comparator: (a, b) => a - b });
679
+ * console.log(heap.isEmpty()); // true;
680
+ * heap.add(1);
681
+ * console.log(heap.isEmpty()); // false;
682
+ */
683
+ isEmpty() {
684
+ return this.size === 0;
685
+ }
686
+ /**
687
+ * Remove all elements.
688
+ * @remarks Time O(1), Space O(1)
689
+ * @returns void
690
+
691
+
692
+
693
+
694
+
695
+
696
+
697
+
698
+
699
+
700
+
701
+
702
+
703
+
704
+
705
+
706
+
707
+
708
+
709
+
710
+
711
+
712
+
713
+
714
+
715
+
716
+
717
+
718
+
719
+ * @example
720
+ * // Remove all elements
721
+ * const heap = new Heap<number>([1, 2, 3], { comparator: (a, b) => a - b });
722
+ * heap.clear();
723
+ * console.log(heap.isEmpty()); // true;
724
+ */
725
+ clear() {
726
+ this._elements = [];
727
+ }
728
+ /**
729
+ * Replace the backing array and rebuild the heap.
730
+ * @remarks Time O(N), Space O(N)
731
+ * @param elements - Iterable used to refill the heap.
732
+ * @returns Array of per-node results from fixing steps.
733
+ */
734
+ refill(elements) {
735
+ this._elements = Array.from(elements);
736
+ return this.fix();
737
+ }
738
+ /**
739
+ * Check if an equal element exists in the heap.
740
+ * @remarks Time O(N), Space O(1)
741
+ * @param element - Element to search for.
742
+ * @returns True if found.
743
+
744
+
745
+
746
+
747
+
748
+
749
+
750
+
751
+
752
+
753
+
754
+
755
+
756
+
757
+
758
+
759
+
760
+
761
+
762
+
763
+
764
+
765
+ * @example
766
+ * // Check element existence
767
+ * const heap = new Heap<number>([3, 1, 2], { comparator: (a, b) => a - b });
768
+ * console.log(heap.has(1)); // true;
769
+ * console.log(heap.has(99)); // false;
770
+ */
771
+ has(element) {
772
+ for (const el of this.elements) if (this._equals(el, element)) return true;
773
+ return false;
774
+ }
775
+ /**
776
+ * Delete one occurrence of an element.
777
+ * @remarks Time O(N), Space O(1)
778
+ * @param element - Element to delete.
779
+ * @returns True if an element was removed.
780
+
781
+
782
+
783
+
784
+
785
+
786
+
787
+
788
+
789
+
790
+
791
+
792
+
793
+
794
+
795
+
796
+
797
+
798
+
799
+
800
+
801
+
802
+
803
+
804
+
805
+
806
+
807
+
808
+ * @example
809
+ * // Remove specific element
810
+ * const heap = new Heap<number>([3, 1, 4, 1, 5], { comparator: (a, b) => a - b });
811
+ * heap.delete(4);
812
+ * console.log(heap.toArray().includes(4)); // false;
813
+ */
814
+ delete(element) {
815
+ let index = -1;
816
+ for (let i = 0; i < this.elements.length; i++) {
817
+ if (this._equals(this.elements[i], element)) {
818
+ index = i;
819
+ break;
820
+ }
821
+ }
822
+ if (index < 0) return false;
823
+ if (index === 0) {
824
+ this.poll();
825
+ } else if (index === this.elements.length - 1) {
826
+ this.elements.pop();
827
+ } else {
828
+ this.elements.splice(index, 1, this.elements.pop());
829
+ this._bubbleUp(index);
830
+ this._sinkDown(index, this.elements.length >> 1);
831
+ }
832
+ return true;
833
+ }
834
+ /**
835
+ * Delete the first element that matches a predicate.
836
+ * @remarks Time O(N), Space O(1)
837
+ * @param predicate - Function (element, index, heap) → boolean.
838
+ * @returns True if an element was removed.
839
+ */
840
+ deleteBy(predicate) {
841
+ let idx = -1;
842
+ for (let i = 0; i < this.elements.length; i++) {
843
+ if (predicate(this.elements[i], i, this)) {
844
+ idx = i;
845
+ break;
846
+ }
847
+ }
848
+ if (idx < 0) return false;
849
+ if (idx === 0) {
850
+ this.poll();
851
+ } else if (idx === this.elements.length - 1) {
852
+ this.elements.pop();
853
+ } else {
854
+ this.elements.splice(idx, 1, this.elements.pop());
855
+ this._bubbleUp(idx);
856
+ this._sinkDown(idx, this.elements.length >> 1);
857
+ }
858
+ return true;
859
+ }
860
+ /**
861
+ * Set the equality comparator used by has/delete operations.
862
+ * @remarks Time O(1), Space O(1)
863
+ * @param equals - Equality predicate (a, b) → boolean.
864
+ * @returns This heap.
865
+ */
866
+ setEquality(equals) {
867
+ this._equals = equals;
868
+ return this;
869
+ }
870
+ /**
871
+ * Traverse the binary heap as a complete binary tree and collect elements.
872
+ * @remarks Time O(N), Space O(H)
873
+ * @param [order] - Traversal order: 'PRE' | 'IN' | 'POST'.
874
+ * @returns Array of visited elements.
875
+
876
+
877
+
878
+
879
+
880
+
881
+
882
+
883
+
884
+
885
+
886
+
887
+
888
+
889
+
890
+
891
+
892
+
893
+
894
+
895
+
896
+
897
+ * @example
898
+ * // Depth-first traversal
899
+ * const heap = new Heap<number>([3, 1, 2], { comparator: (a, b) => a - b });
900
+ * const result = heap.dfs('IN');
901
+ * console.log(result.length); // 3;
902
+ */
903
+ dfs(order = "PRE") {
904
+ const result = [];
905
+ const _dfs = /* @__PURE__ */ __name((index) => {
906
+ const left = 2 * index + 1, right = left + 1;
907
+ if (index < this.size) {
908
+ if (order === "IN") {
909
+ _dfs(left);
910
+ result.push(this.elements[index]);
911
+ _dfs(right);
912
+ } else if (order === "PRE") {
913
+ result.push(this.elements[index]);
914
+ _dfs(left);
915
+ _dfs(right);
916
+ } else if (order === "POST") {
917
+ _dfs(left);
918
+ _dfs(right);
919
+ result.push(this.elements[index]);
920
+ }
921
+ }
922
+ }, "_dfs");
923
+ _dfs(0);
924
+ return result;
925
+ }
926
+ /**
927
+ * Restore heap order bottom-up (heapify in-place).
928
+ * @remarks Time O(N), Space O(1)
929
+ * @returns Array of per-node results from fixing steps.
930
+ */
931
+ fix() {
932
+ const results = [];
933
+ for (let i = Math.floor(this.size / 2) - 1; i >= 0; i--) {
934
+ results.push(this._sinkDown(i, this.elements.length >> 1));
935
+ }
936
+ return results;
937
+ }
938
+ /**
939
+ * Return all elements in ascending order by repeatedly polling.
940
+ * @remarks Time O(N log N), Space O(N)
941
+ * @returns Sorted array of elements.
942
+
943
+
944
+
945
+
946
+
947
+
948
+
949
+
950
+
951
+
952
+
953
+
954
+
955
+
956
+
957
+
958
+
959
+
960
+
961
+
962
+
963
+
964
+
965
+
966
+
967
+
968
+
969
+
970
+
971
+
972
+
973
+ * @example
974
+ * // Sort elements using heap
975
+ * const heap = new Heap<number>([5, 1, 3, 2, 4]);
976
+ * const sorted = heap.sort();
977
+ * console.log(sorted); // [1, 2, 3, 4, 5];
978
+ */
979
+ sort() {
980
+ const visited = [];
981
+ const cloned = this._createInstance();
982
+ for (const x of this.elements) cloned.add(x);
983
+ while (!cloned.isEmpty()) {
984
+ const top = cloned.poll();
985
+ if (top !== void 0) visited.push(top);
986
+ }
987
+ return visited;
988
+ }
989
+ /**
990
+ * Deep clone this heap.
991
+ * @remarks Time O(N), Space O(N)
992
+ * @returns A new heap with the same elements.
993
+
994
+
995
+
996
+
997
+
998
+
999
+
1000
+
1001
+
1002
+
1003
+
1004
+
1005
+
1006
+
1007
+
1008
+
1009
+
1010
+
1011
+
1012
+
1013
+
1014
+
1015
+
1016
+
1017
+
1018
+
1019
+
1020
+
1021
+
1022
+ * @example
1023
+ * // Create independent copy
1024
+ * const heap = new Heap<number>([3, 1, 4], { comparator: (a, b) => a - b });
1025
+ * const copy = heap.clone();
1026
+ * copy.poll();
1027
+ * console.log(heap.size); // 3;
1028
+ * console.log(copy.size); // 2;
1029
+ */
1030
+ clone() {
1031
+ const next = this._createInstance();
1032
+ for (const x of this.elements) next.add(x);
1033
+ return next;
1034
+ }
1035
+ /**
1036
+ * Filter elements into a new heap of the same class.
1037
+ * @remarks Time O(N log N), Space O(N)
1038
+ * @param callback - Predicate (element, index, heap) → boolean to keep element.
1039
+ * @param [thisArg] - Value for `this` inside the callback.
1040
+ * @returns A new heap with the kept elements.
1041
+
1042
+
1043
+
1044
+
1045
+
1046
+
1047
+
1048
+
1049
+
1050
+
1051
+
1052
+
1053
+
1054
+
1055
+
1056
+
1057
+
1058
+
1059
+
1060
+
1061
+
1062
+
1063
+
1064
+
1065
+
1066
+
1067
+
1068
+
1069
+
1070
+ * @example
1071
+ * // Filter elements
1072
+ * const heap = new Heap<number>([1, 2, 3, 4, 5], { comparator: (a, b) => a - b });
1073
+ * const evens = heap.filter(x => x % 2 === 0);
1074
+ * console.log(evens.size); // 2;
1075
+ */
1076
+ filter(callback, thisArg) {
1077
+ const out = this._createInstance();
1078
+ let i = 0;
1079
+ for (const x of this) {
1080
+ if (thisArg === void 0 ? callback(x, i++, this) : callback.call(thisArg, x, i++, this)) {
1081
+ out.add(x);
1082
+ } else {
1083
+ i++;
1084
+ }
1085
+ }
1086
+ return out;
1087
+ }
1088
+ /**
1089
+ * Map elements into a new heap of possibly different element type.
1090
+ * @remarks Time O(N log N), Space O(N)
1091
+ * @template EM
1092
+ * @template RM
1093
+ * @param callback - Mapping function (element, index, heap) → newElement.
1094
+ * @param options - Options for the output heap, including comparator for EM.
1095
+ * @param [thisArg] - Value for `this` inside the callback.
1096
+ * @returns A new heap with mapped elements.
1097
+
1098
+
1099
+
1100
+
1101
+
1102
+
1103
+
1104
+
1105
+
1106
+
1107
+
1108
+
1109
+
1110
+
1111
+
1112
+
1113
+
1114
+
1115
+
1116
+
1117
+
1118
+
1119
+
1120
+
1121
+
1122
+
1123
+
1124
+
1125
+ * @example
1126
+ * // Transform elements
1127
+ * const heap = new Heap<number>([1, 2, 3], { comparator: (a, b) => a - b });
1128
+ * const doubled = heap.map(x => x * 2, { comparator: (a, b) => a - b });
1129
+ * console.log(doubled.peek()); // 2;
1130
+ */
1131
+ map(callback, options, thisArg) {
1132
+ const { comparator, toElementFn, ...rest } = options ?? {};
1133
+ if (!comparator) throw new TypeError(ERR.comparatorRequired("Heap.map"));
1134
+ const out = this._createLike([], { ...rest, comparator, toElementFn });
1135
+ let i = 0;
1136
+ for (const x of this) {
1137
+ const v = thisArg === void 0 ? callback(x, i++, this) : callback.call(thisArg, x, i++, this);
1138
+ out.add(v);
1139
+ }
1140
+ return out;
1141
+ }
1142
+ /**
1143
+ * Map elements into a new heap of the same element type.
1144
+ * @remarks Time O(N log N), Space O(N)
1145
+ * @param callback - Mapping function (element, index, heap) → element.
1146
+ * @param [thisArg] - Value for `this` inside the callback.
1147
+ * @returns A new heap with mapped elements.
1148
+ */
1149
+ mapSame(callback, thisArg) {
1150
+ const out = this._createInstance();
1151
+ let i = 0;
1152
+ for (const x of this) {
1153
+ const v = thisArg === void 0 ? callback(x, i++, this) : callback.call(thisArg, x, i++, this);
1154
+ out.add(v);
1155
+ }
1156
+ return out;
1157
+ }
1158
+ _DEFAULT_COMPARATOR = /* @__PURE__ */ __name((a, b) => {
1159
+ if (typeof a === "object" || typeof b === "object") {
1160
+ throw new TypeError(ERR.comparatorRequired("Heap"));
1161
+ }
1162
+ if (a > b) return 1;
1163
+ if (a < b) return -1;
1164
+ return 0;
1165
+ }, "_DEFAULT_COMPARATOR");
1166
+ _comparator = this._DEFAULT_COMPARATOR;
1167
+ /**
1168
+ * Get the comparator used to order elements.
1169
+ * @remarks Time O(1), Space O(1)
1170
+ * @returns Comparator function.
1171
+ */
1172
+ get comparator() {
1173
+ return this._comparator;
1174
+ }
1175
+ *_getIterator() {
1176
+ for (const element of this.elements) yield element;
1177
+ }
1178
+ _bubbleUp(index) {
1179
+ const element = this.elements[index];
1180
+ while (index > 0) {
1181
+ const parent = index - 1 >> 1;
1182
+ const parentItem = this.elements[parent];
1183
+ if (this.comparator(parentItem, element) <= 0) break;
1184
+ this.elements[index] = parentItem;
1185
+ index = parent;
1186
+ }
1187
+ this.elements[index] = element;
1188
+ return true;
1189
+ }
1190
+ _sinkDown(index, halfLength) {
1191
+ const element = this.elements[index];
1192
+ while (index < halfLength) {
1193
+ let left = index << 1 | 1;
1194
+ const right = left + 1;
1195
+ let minItem = this.elements[left];
1196
+ if (right < this.elements.length && this.comparator(minItem, this.elements[right]) > 0) {
1197
+ left = right;
1198
+ minItem = this.elements[right];
1199
+ }
1200
+ if (this.comparator(minItem, element) >= 0) break;
1201
+ this.elements[index] = minItem;
1202
+ index = left;
1203
+ }
1204
+ this.elements[index] = element;
1205
+ return true;
1206
+ }
1207
+ /**
1208
+ * (Protected) Create an empty instance of the same concrete class.
1209
+ * @remarks Time O(1), Space O(1)
1210
+ * @param [options] - Options to override comparator or toElementFn.
1211
+ * @returns A like-kind empty heap instance.
1212
+ */
1213
+ _createInstance(options) {
1214
+ const Ctor = this.constructor;
1215
+ return new Ctor([], { comparator: this.comparator, toElementFn: this.toElementFn, ...options ?? {} });
1216
+ }
1217
+ /**
1218
+ * (Protected) Create a like-kind instance seeded by elements.
1219
+ * @remarks Time O(N log N), Space O(N)
1220
+ * @template EM
1221
+ * @template RM
1222
+ * @param [elements] - Iterable of elements or raw values to seed.
1223
+ * @param [options] - Options forwarded to the constructor.
1224
+ * @returns A like-kind heap instance.
1225
+ */
1226
+ _createLike(elements = [], options) {
1227
+ const Ctor = this.constructor;
1228
+ return new Ctor(elements, options);
1229
+ }
1230
+ /**
1231
+ * (Protected) Spawn an empty like-kind heap instance.
1232
+ * @remarks Time O(1), Space O(1)
1233
+ * @template EM
1234
+ * @template RM
1235
+ * @param [options] - Options forwarded to the constructor.
1236
+ * @returns An empty like-kind heap instance.
1237
+ */
1238
+ _spawnLike(options) {
1239
+ return this._createLike([], options);
1240
+ }
1241
+ };
1242
+ var FibonacciHeapNode = class {
1243
+ static {
1244
+ __name(this, "FibonacciHeapNode");
1245
+ }
1246
+ element;
1247
+ degree;
1248
+ left;
1249
+ right;
1250
+ child;
1251
+ parent;
1252
+ marked;
1253
+ constructor(element, degree = 0) {
1254
+ this.element = element;
1255
+ this.degree = degree;
1256
+ this.marked = false;
1257
+ }
1258
+ };
1259
+ var FibonacciHeap = class {
1260
+ static {
1261
+ __name(this, "FibonacciHeap");
1262
+ }
1263
+ /**
1264
+ * Create a FibonacciHeap.
1265
+ * @remarks Time O(1), Space O(1)
1266
+ * @param [comparator] - Comparator to order elements (min-heap by default).
1267
+ * @returns New FibonacciHeap instance.
1268
+ */
1269
+ constructor(comparator) {
1270
+ this.clear();
1271
+ this._comparator = comparator || this._defaultComparator;
1272
+ if (typeof this.comparator !== "function") throw new TypeError(ERR.notAFunction("comparator", "FibonacciHeap"));
1273
+ }
1274
+ _root;
1275
+ /**
1276
+ * Get the circular root list head.
1277
+ * @remarks Time O(1), Space O(1)
1278
+ * @returns Root node or undefined.
1279
+ */
1280
+ get root() {
1281
+ return this._root;
1282
+ }
1283
+ _size = 0;
1284
+ get size() {
1285
+ return this._size;
1286
+ }
1287
+ _min;
1288
+ /**
1289
+ * Get the current minimum node.
1290
+ * @remarks Time O(1), Space O(1)
1291
+ * @returns Min node or undefined.
1292
+ */
1293
+ get min() {
1294
+ return this._min;
1295
+ }
1296
+ _comparator;
1297
+ get comparator() {
1298
+ return this._comparator;
1299
+ }
1300
+ clear() {
1301
+ this._root = void 0;
1302
+ this._min = void 0;
1303
+ this._size = 0;
1304
+ }
1305
+ add(element) {
1306
+ this.push(element);
1307
+ return true;
1308
+ }
1309
+ /**
1310
+ * Push an element into the root list.
1311
+ * @remarks Time O(1) amortized, Space O(1)
1312
+ * @param element - Element to insert.
1313
+ * @returns This heap.
1314
+ */
1315
+ push(element) {
1316
+ const node = this.createNode(element);
1317
+ node.left = node;
1318
+ node.right = node;
1319
+ this.mergeWithRoot(node);
1320
+ if (!this.min || this.comparator(node.element, this.min.element) <= 0) this._min = node;
1321
+ this._size++;
1322
+ return this;
1323
+ }
1324
+ peek() {
1325
+ return this.min ? this.min.element : void 0;
1326
+ }
1327
+ /**
1328
+ * Collect nodes from a circular doubly linked list starting at head.
1329
+ * @remarks Time O(K), Space O(K)
1330
+ * @param [head] - Start node of the circular list.
1331
+ * @returns Array of nodes from the list.
1332
+ */
1333
+ consumeLinkedList(head) {
1334
+ const elements = [];
1335
+ if (!head) return elements;
1336
+ let node = head;
1337
+ let started = false;
1338
+ while (true) {
1339
+ if (node === head && started) break;
1340
+ else if (node === head) started = true;
1341
+ elements.push(node);
1342
+ node = node.right;
1343
+ }
1344
+ return elements;
1345
+ }
1346
+ /**
1347
+ * Insert a node into a parent's child list (circular).
1348
+ * @remarks Time O(1), Space O(1)
1349
+ * @param parent - Parent node.
1350
+ * @param node - Child node to insert.
1351
+ * @returns void
1352
+ */
1353
+ mergeWithChild(parent, node) {
1354
+ if (!parent.child) parent.child = node;
1355
+ else {
1356
+ node.right = parent.child.right;
1357
+ node.left = parent.child;
1358
+ parent.child.right.left = node;
1359
+ parent.child.right = node;
1360
+ }
1361
+ }
1362
+ poll() {
1363
+ return this.pop();
1364
+ }
1365
+ /**
1366
+ * Remove and return the minimum element, consolidating the root list.
1367
+ * @remarks Time O(log N) amortized, Space O(1)
1368
+ * @returns Minimum element or undefined.
1369
+ */
1370
+ pop() {
1371
+ if (this._size === 0) return void 0;
1372
+ const z = this.min;
1373
+ if (z.child) {
1374
+ const elements = this.consumeLinkedList(z.child);
1375
+ for (const node of elements) {
1376
+ this.mergeWithRoot(node);
1377
+ node.parent = void 0;
1378
+ }
1379
+ }
1380
+ this.removeFromRoot(z);
1381
+ if (z === z.right) {
1382
+ this._min = void 0;
1383
+ this._root = void 0;
1384
+ } else {
1385
+ this._min = z.right;
1386
+ this._consolidate();
1387
+ }
1388
+ this._size--;
1389
+ return z.element;
1390
+ }
1391
+ /**
1392
+ * Meld another heap into this heap.
1393
+ * @remarks Time O(1), Space O(1)
1394
+ * @param heapToMerge - Another FibonacciHeap to meld into this one.
1395
+ * @returns void
1396
+ */
1397
+ merge(heapToMerge) {
1398
+ if (heapToMerge.size === 0) return;
1399
+ if (this.root && heapToMerge.root) {
1400
+ const thisRoot = this.root, otherRoot = heapToMerge.root;
1401
+ const thisRootRight = thisRoot.right, otherRootLeft = otherRoot.left;
1402
+ thisRoot.right = otherRoot;
1403
+ otherRoot.left = thisRoot;
1404
+ thisRootRight.left = otherRootLeft;
1405
+ otherRootLeft.right = thisRootRight;
1406
+ } else if (!this.root && heapToMerge.root) {
1407
+ this._root = heapToMerge.root;
1408
+ }
1409
+ if (!this.min || heapToMerge.min && this.comparator(heapToMerge.min.element, this.min.element) < 0) {
1410
+ this._min = heapToMerge.min;
1411
+ }
1412
+ this._size += heapToMerge.size;
1413
+ heapToMerge.clear();
1414
+ }
1415
+ createNode(element) {
1416
+ return new FibonacciHeapNode(element);
1417
+ }
1418
+ isEmpty() {
1419
+ return this._size === 0;
1420
+ }
1421
+ _defaultComparator(a, b) {
1422
+ if (a < b) return -1;
1423
+ if (a > b) return 1;
1424
+ return 0;
1425
+ }
1426
+ mergeWithRoot(node) {
1427
+ if (!this.root) this._root = node;
1428
+ else {
1429
+ node.right = this.root.right;
1430
+ node.left = this.root;
1431
+ this.root.right.left = node;
1432
+ this.root.right = node;
1433
+ }
1434
+ }
1435
+ removeFromRoot(node) {
1436
+ if (this.root === node) this._root = node.right;
1437
+ if (node.left) node.left.right = node.right;
1438
+ if (node.right) node.right.left = node.left;
1439
+ }
1440
+ _link(y, x) {
1441
+ this.removeFromRoot(y);
1442
+ y.left = y;
1443
+ y.right = y;
1444
+ this.mergeWithChild(x, y);
1445
+ x.degree++;
1446
+ y.parent = x;
1447
+ }
1448
+ _consolidate() {
1449
+ const A = new Array(this._size);
1450
+ const elements = this.consumeLinkedList(this.root);
1451
+ let x, y, d, t;
1452
+ for (const node of elements) {
1453
+ x = node;
1454
+ d = x.degree;
1455
+ while (A[d]) {
1456
+ y = A[d];
1457
+ if (this.comparator(x.element, y.element) > 0) {
1458
+ t = x;
1459
+ x = y;
1460
+ y = t;
1461
+ }
1462
+ this._link(y, x);
1463
+ A[d] = void 0;
1464
+ d++;
1465
+ }
1466
+ A[d] = x;
1467
+ }
1468
+ for (let i = 0; i < A.length; i++) {
1469
+ if (A[i] && (!this.min || this.comparator(A[i].element, this.min.element) <= 0)) this._min = A[i];
1470
+ }
1471
+ }
1472
+ };
1473
+
1474
+ // src/data-structures/heap/max-heap.ts
1475
+ var MaxHeap = class extends Heap {
1476
+ static {
1477
+ __name(this, "MaxHeap");
1478
+ }
1479
+ /**
1480
+ * Create a max-heap. For objects, supply a custom comparator.
1481
+ * @param elements Optional initial elements.
1482
+ * @param options Optional configuration.
1483
+ */
1484
+ constructor(elements = [], options) {
1485
+ super(elements, {
1486
+ comparator: /* @__PURE__ */ __name((a, b) => {
1487
+ if (typeof a === "object" || typeof b === "object") {
1488
+ throw new TypeError(ERR.comparatorRequired("MaxHeap"));
1489
+ }
1490
+ if (a < b) return 1;
1491
+ if (a > b) return -1;
1492
+ return 0;
1493
+ }, "comparator"),
1494
+ ...options
1495
+ });
1496
+ }
1497
+ };
1498
+
1499
+ // src/data-structures/heap/min-heap.ts
1500
+ var MinHeap = class extends Heap {
1501
+ static {
1502
+ __name(this, "MinHeap");
1503
+ }
1504
+ /**
1505
+ * Create a min-heap.
1506
+ * @param elements Optional initial elements.
1507
+ * @param options Optional configuration.
1508
+ */
1509
+ constructor(elements = [], options) {
1510
+ super(elements, options);
1511
+ }
1512
+ };
1513
+ /**
1514
+ * data-structure-typed
1515
+ *
1516
+ * @author Pablo Zeng
1517
+ * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>
1518
+ * @license MIT License
1519
+ */
1520
+ /**
1521
+ * data-structure-typed
1522
+ * @author Kirk Qi
1523
+ * @copyright Copyright (c) 2022 Kirk Qi <qilinaus@gmail.com>
1524
+ * @license MIT License
1525
+ */
1526
+ /**
1527
+ * @remarks Time O(n log n), Space O(n).
1528
+ * data-structure-typed
1529
+ * @author Kirk Qi
1530
+ * @copyright Copyright (c) 2022 Kirk Qi <qilinaus@gmail.com>
1531
+ * @license MIT License
1532
+ */
1533
+
1534
+ exports.FibonacciHeap = FibonacciHeap;
1535
+ exports.FibonacciHeapNode = FibonacciHeapNode;
1536
+ exports.Heap = Heap;
1537
+ exports.MaxHeap = MaxHeap;
1538
+ exports.MinHeap = MinHeap;
1539
+ //# sourceMappingURL=heap.cjs.map
1540
+ //# sourceMappingURL=heap.cjs.map