data-structure-typed 2.5.0 → 2.5.2

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