tree-set-typed 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (273) hide show
  1. package/.eslintrc.js +61 -0
  2. package/.prettierignore +6 -0
  3. package/.prettierrc.js +16 -0
  4. package/LICENSE +21 -0
  5. package/README.md +482 -0
  6. package/coverage/clover.xml +13 -0
  7. package/coverage/coverage-final.json +96 -0
  8. package/coverage/coverage-summary.json +60 -0
  9. package/coverage/lcov-report/base.css +403 -0
  10. package/coverage/lcov-report/block-navigation.js +87 -0
  11. package/coverage/lcov-report/favicon.png +0 -0
  12. package/coverage/lcov-report/index.html +119 -0
  13. package/coverage/lcov-report/index.ts.html +109 -0
  14. package/coverage/lcov-report/prettify.css +1 -0
  15. package/coverage/lcov-report/prettify.js +2 -0
  16. package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  17. package/coverage/lcov-report/sorter.js +206 -0
  18. package/coverage/lcov.info +14 -0
  19. package/dist/cjs/index.cjs +12 -0
  20. package/dist/cjs/index.cjs.map +1 -0
  21. package/dist/cjs-legacy/index.cjs +12 -0
  22. package/dist/cjs-legacy/index.cjs.map +1 -0
  23. package/dist/esm/index.mjs +3 -0
  24. package/dist/esm/index.mjs.map +1 -0
  25. package/dist/esm-legacy/index.mjs +3 -0
  26. package/dist/esm-legacy/index.mjs.map +1 -0
  27. package/dist/types/common/index.d.ts +12 -0
  28. package/dist/types/constants/index.d.ts +4 -0
  29. package/dist/types/data-structures/base/index.d.ts +2 -0
  30. package/dist/types/data-structures/base/iterable-element-base.d.ts +219 -0
  31. package/dist/types/data-structures/base/iterable-entry-base.d.ts +150 -0
  32. package/dist/types/data-structures/base/linear-base.d.ts +335 -0
  33. package/dist/types/data-structures/binary-tree/avl-tree-counter.d.ts +236 -0
  34. package/dist/types/data-structures/binary-tree/avl-tree-multi-map.d.ts +197 -0
  35. package/dist/types/data-structures/binary-tree/avl-tree.d.ts +440 -0
  36. package/dist/types/data-structures/binary-tree/binary-indexed-tree.d.ts +174 -0
  37. package/dist/types/data-structures/binary-tree/binary-tree.d.ts +807 -0
  38. package/dist/types/data-structures/binary-tree/bst.d.ts +645 -0
  39. package/dist/types/data-structures/binary-tree/index.d.ts +10 -0
  40. package/dist/types/data-structures/binary-tree/red-black-tree.d.ts +312 -0
  41. package/dist/types/data-structures/binary-tree/segment-tree.d.ts +160 -0
  42. package/dist/types/data-structures/binary-tree/tree-counter.d.ts +243 -0
  43. package/dist/types/data-structures/binary-tree/tree-multi-map.d.ts +333 -0
  44. package/dist/types/data-structures/graph/abstract-graph.d.ts +340 -0
  45. package/dist/types/data-structures/graph/directed-graph.d.ts +332 -0
  46. package/dist/types/data-structures/graph/index.d.ts +4 -0
  47. package/dist/types/data-structures/graph/map-graph.d.ts +78 -0
  48. package/dist/types/data-structures/graph/undirected-graph.d.ts +347 -0
  49. package/dist/types/data-structures/hash/hash-map.d.ts +428 -0
  50. package/dist/types/data-structures/hash/index.d.ts +1 -0
  51. package/dist/types/data-structures/heap/heap.d.ts +552 -0
  52. package/dist/types/data-structures/heap/index.d.ts +3 -0
  53. package/dist/types/data-structures/heap/max-heap.d.ts +32 -0
  54. package/dist/types/data-structures/heap/min-heap.d.ts +33 -0
  55. package/dist/types/data-structures/index.d.ts +12 -0
  56. package/dist/types/data-structures/linked-list/doubly-linked-list.d.ts +437 -0
  57. package/dist/types/data-structures/linked-list/index.d.ts +3 -0
  58. package/dist/types/data-structures/linked-list/singly-linked-list.d.ts +567 -0
  59. package/dist/types/data-structures/linked-list/skip-linked-list.d.ts +27 -0
  60. package/dist/types/data-structures/matrix/index.d.ts +2 -0
  61. package/dist/types/data-structures/matrix/matrix.d.ts +168 -0
  62. package/dist/types/data-structures/matrix/navigator.d.ts +55 -0
  63. package/dist/types/data-structures/priority-queue/index.d.ts +3 -0
  64. package/dist/types/data-structures/priority-queue/max-priority-queue.d.ts +27 -0
  65. package/dist/types/data-structures/priority-queue/min-priority-queue.d.ts +26 -0
  66. package/dist/types/data-structures/priority-queue/priority-queue.d.ts +15 -0
  67. package/dist/types/data-structures/queue/deque.d.ts +459 -0
  68. package/dist/types/data-structures/queue/index.d.ts +2 -0
  69. package/dist/types/data-structures/queue/queue.d.ts +364 -0
  70. package/dist/types/data-structures/stack/index.d.ts +1 -0
  71. package/dist/types/data-structures/stack/stack.d.ts +324 -0
  72. package/dist/types/data-structures/tree/index.d.ts +1 -0
  73. package/dist/types/data-structures/tree/tree.d.ts +62 -0
  74. package/dist/types/data-structures/trie/index.d.ts +1 -0
  75. package/dist/types/data-structures/trie/trie.d.ts +412 -0
  76. package/dist/types/index.d.ts +23 -0
  77. package/dist/types/interfaces/binary-tree.d.ts +60 -0
  78. package/dist/types/interfaces/doubly-linked-list.d.ts +1 -0
  79. package/dist/types/interfaces/graph.d.ts +21 -0
  80. package/dist/types/interfaces/heap.d.ts +1 -0
  81. package/dist/types/interfaces/index.d.ts +8 -0
  82. package/dist/types/interfaces/navigator.d.ts +1 -0
  83. package/dist/types/interfaces/priority-queue.d.ts +1 -0
  84. package/dist/types/interfaces/segment-tree.d.ts +1 -0
  85. package/dist/types/interfaces/singly-linked-list.d.ts +1 -0
  86. package/dist/types/types/common.d.ts +15 -0
  87. package/dist/types/types/data-structures/base/base.d.ts +13 -0
  88. package/dist/types/types/data-structures/base/index.d.ts +1 -0
  89. package/dist/types/types/data-structures/binary-tree/avl-tree-counter.d.ts +2 -0
  90. package/dist/types/types/data-structures/binary-tree/avl-tree-multi-map.d.ts +2 -0
  91. package/dist/types/types/data-structures/binary-tree/avl-tree.d.ts +2 -0
  92. package/dist/types/types/data-structures/binary-tree/binary-indexed-tree.d.ts +1 -0
  93. package/dist/types/types/data-structures/binary-tree/binary-tree.d.ts +29 -0
  94. package/dist/types/types/data-structures/binary-tree/bst.d.ts +12 -0
  95. package/dist/types/types/data-structures/binary-tree/index.d.ts +9 -0
  96. package/dist/types/types/data-structures/binary-tree/red-black-tree.d.ts +3 -0
  97. package/dist/types/types/data-structures/binary-tree/segment-tree.d.ts +1 -0
  98. package/dist/types/types/data-structures/binary-tree/tree-counter.d.ts +2 -0
  99. package/dist/types/types/data-structures/binary-tree/tree-multi-map.d.ts +2 -0
  100. package/dist/types/types/data-structures/graph/abstract-graph.d.ts +14 -0
  101. package/dist/types/types/data-structures/graph/directed-graph.d.ts +1 -0
  102. package/dist/types/types/data-structures/graph/index.d.ts +3 -0
  103. package/dist/types/types/data-structures/graph/map-graph.d.ts +1 -0
  104. package/dist/types/types/data-structures/graph/undirected-graph.d.ts +1 -0
  105. package/dist/types/types/data-structures/hash/hash-map.d.ts +19 -0
  106. package/dist/types/types/data-structures/hash/index.d.ts +2 -0
  107. package/dist/types/types/data-structures/heap/heap.d.ts +5 -0
  108. package/dist/types/types/data-structures/heap/index.d.ts +1 -0
  109. package/dist/types/types/data-structures/heap/max-heap.d.ts +1 -0
  110. package/dist/types/types/data-structures/heap/min-heap.d.ts +1 -0
  111. package/dist/types/types/data-structures/index.d.ts +12 -0
  112. package/dist/types/types/data-structures/linked-list/doubly-linked-list.d.ts +2 -0
  113. package/dist/types/types/data-structures/linked-list/index.d.ts +3 -0
  114. package/dist/types/types/data-structures/linked-list/singly-linked-list.d.ts +2 -0
  115. package/dist/types/types/data-structures/linked-list/skip-linked-list.d.ts +4 -0
  116. package/dist/types/types/data-structures/matrix/index.d.ts +2 -0
  117. package/dist/types/types/data-structures/matrix/matrix.d.ts +7 -0
  118. package/dist/types/types/data-structures/matrix/navigator.d.ts +14 -0
  119. package/dist/types/types/data-structures/priority-queue/index.d.ts +3 -0
  120. package/dist/types/types/data-structures/priority-queue/max-priority-queue.d.ts +1 -0
  121. package/dist/types/types/data-structures/priority-queue/min-priority-queue.d.ts +1 -0
  122. package/dist/types/types/data-structures/priority-queue/priority-queue.d.ts +2 -0
  123. package/dist/types/types/data-structures/queue/deque.d.ts +4 -0
  124. package/dist/types/types/data-structures/queue/index.d.ts +2 -0
  125. package/dist/types/types/data-structures/queue/queue.d.ts +4 -0
  126. package/dist/types/types/data-structures/stack/index.d.ts +1 -0
  127. package/dist/types/types/data-structures/stack/stack.d.ts +2 -0
  128. package/dist/types/types/data-structures/tree/index.d.ts +1 -0
  129. package/dist/types/types/data-structures/tree/tree.d.ts +1 -0
  130. package/dist/types/types/data-structures/trie/index.d.ts +1 -0
  131. package/dist/types/types/data-structures/trie/trie.d.ts +4 -0
  132. package/dist/types/types/index.d.ts +3 -0
  133. package/dist/types/types/utils/index.d.ts +2 -0
  134. package/dist/types/types/utils/utils.d.ts +22 -0
  135. package/dist/types/types/utils/validate-type.d.ts +19 -0
  136. package/dist/types/utils/index.d.ts +2 -0
  137. package/dist/types/utils/number.d.ts +14 -0
  138. package/dist/types/utils/utils.d.ts +209 -0
  139. package/dist/umd/red-black-tree-typed.js +14578 -0
  140. package/dist/umd/red-black-tree-typed.js.map +1 -0
  141. package/dist/umd/red-black-tree-typed.min.js +44 -0
  142. package/dist/umd/red-black-tree-typed.min.js.map +1 -0
  143. package/docs/.nojekyll +1 -0
  144. package/docs/assets/highlight.css +92 -0
  145. package/docs/assets/main.js +59 -0
  146. package/docs/assets/navigation.js +1 -0
  147. package/docs/assets/search.js +1 -0
  148. package/docs/assets/style.css +1383 -0
  149. package/docs/classes/AVLTree.html +2046 -0
  150. package/docs/classes/AVLTreeNode.html +263 -0
  151. package/docs/index.html +523 -0
  152. package/docs/modules.html +45 -0
  153. package/jest.config.js +8 -0
  154. package/package.json +113 -0
  155. package/src/common/index.ts +23 -0
  156. package/src/constants/index.ts +4 -0
  157. package/src/data-structures/base/index.ts +2 -0
  158. package/src/data-structures/base/iterable-element-base.ts +352 -0
  159. package/src/data-structures/base/iterable-entry-base.ts +246 -0
  160. package/src/data-structures/base/linear-base.ts +643 -0
  161. package/src/data-structures/binary-tree/avl-tree-counter.ts +539 -0
  162. package/src/data-structures/binary-tree/avl-tree-multi-map.ts +438 -0
  163. package/src/data-structures/binary-tree/avl-tree.ts +840 -0
  164. package/src/data-structures/binary-tree/binary-indexed-tree.ts +331 -0
  165. package/src/data-structures/binary-tree/binary-tree.ts +2492 -0
  166. package/src/data-structures/binary-tree/bst.ts +2024 -0
  167. package/src/data-structures/binary-tree/index.ts +10 -0
  168. package/src/data-structures/binary-tree/red-black-tree.ts +767 -0
  169. package/src/data-structures/binary-tree/segment-tree.ts +324 -0
  170. package/src/data-structures/binary-tree/tree-counter.ts +575 -0
  171. package/src/data-structures/binary-tree/tree-multi-map.ts +549 -0
  172. package/src/data-structures/graph/abstract-graph.ts +1081 -0
  173. package/src/data-structures/graph/directed-graph.ts +715 -0
  174. package/src/data-structures/graph/index.ts +4 -0
  175. package/src/data-structures/graph/map-graph.ts +132 -0
  176. package/src/data-structures/graph/undirected-graph.ts +626 -0
  177. package/src/data-structures/hash/hash-map.ts +813 -0
  178. package/src/data-structures/hash/index.ts +1 -0
  179. package/src/data-structures/heap/heap.ts +1020 -0
  180. package/src/data-structures/heap/index.ts +3 -0
  181. package/src/data-structures/heap/max-heap.ts +47 -0
  182. package/src/data-structures/heap/min-heap.ts +36 -0
  183. package/src/data-structures/index.ts +12 -0
  184. package/src/data-structures/linked-list/doubly-linked-list.ts +876 -0
  185. package/src/data-structures/linked-list/index.ts +3 -0
  186. package/src/data-structures/linked-list/singly-linked-list.ts +1050 -0
  187. package/src/data-structures/linked-list/skip-linked-list.ts +173 -0
  188. package/src/data-structures/matrix/index.ts +2 -0
  189. package/src/data-structures/matrix/matrix.ts +491 -0
  190. package/src/data-structures/matrix/navigator.ts +124 -0
  191. package/src/data-structures/priority-queue/index.ts +3 -0
  192. package/src/data-structures/priority-queue/max-priority-queue.ts +42 -0
  193. package/src/data-structures/priority-queue/min-priority-queue.ts +29 -0
  194. package/src/data-structures/priority-queue/priority-queue.ts +19 -0
  195. package/src/data-structures/queue/deque.ts +1001 -0
  196. package/src/data-structures/queue/index.ts +2 -0
  197. package/src/data-structures/queue/queue.ts +592 -0
  198. package/src/data-structures/stack/index.ts +1 -0
  199. package/src/data-structures/stack/stack.ts +469 -0
  200. package/src/data-structures/tree/index.ts +1 -0
  201. package/src/data-structures/tree/tree.ts +115 -0
  202. package/src/data-structures/trie/index.ts +1 -0
  203. package/src/data-structures/trie/trie.ts +756 -0
  204. package/src/index.ts +24 -0
  205. package/src/interfaces/binary-tree.ts +252 -0
  206. package/src/interfaces/doubly-linked-list.ts +1 -0
  207. package/src/interfaces/graph.ts +44 -0
  208. package/src/interfaces/heap.ts +1 -0
  209. package/src/interfaces/index.ts +8 -0
  210. package/src/interfaces/navigator.ts +1 -0
  211. package/src/interfaces/priority-queue.ts +1 -0
  212. package/src/interfaces/segment-tree.ts +1 -0
  213. package/src/interfaces/singly-linked-list.ts +1 -0
  214. package/src/types/common.ts +25 -0
  215. package/src/types/data-structures/base/base.ts +34 -0
  216. package/src/types/data-structures/base/index.ts +1 -0
  217. package/src/types/data-structures/binary-tree/avl-tree-counter.ts +3 -0
  218. package/src/types/data-structures/binary-tree/avl-tree-multi-map.ts +3 -0
  219. package/src/types/data-structures/binary-tree/avl-tree.ts +3 -0
  220. package/src/types/data-structures/binary-tree/binary-indexed-tree.ts +1 -0
  221. package/src/types/data-structures/binary-tree/binary-tree.ts +31 -0
  222. package/src/types/data-structures/binary-tree/bst.ts +19 -0
  223. package/src/types/data-structures/binary-tree/index.ts +9 -0
  224. package/src/types/data-structures/binary-tree/red-black-tree.ts +5 -0
  225. package/src/types/data-structures/binary-tree/segment-tree.ts +1 -0
  226. package/src/types/data-structures/binary-tree/tree-counter.ts +3 -0
  227. package/src/types/data-structures/binary-tree/tree-multi-map.ts +3 -0
  228. package/src/types/data-structures/graph/abstract-graph.ts +18 -0
  229. package/src/types/data-structures/graph/directed-graph.ts +2 -0
  230. package/src/types/data-structures/graph/index.ts +3 -0
  231. package/src/types/data-structures/graph/map-graph.ts +1 -0
  232. package/src/types/data-structures/graph/undirected-graph.ts +1 -0
  233. package/src/types/data-structures/hash/hash-map.ts +19 -0
  234. package/src/types/data-structures/hash/index.ts +3 -0
  235. package/src/types/data-structures/heap/heap.ts +6 -0
  236. package/src/types/data-structures/heap/index.ts +1 -0
  237. package/src/types/data-structures/heap/max-heap.ts +1 -0
  238. package/src/types/data-structures/heap/min-heap.ts +1 -0
  239. package/src/types/data-structures/index.ts +12 -0
  240. package/src/types/data-structures/linked-list/doubly-linked-list.ts +3 -0
  241. package/src/types/data-structures/linked-list/index.ts +3 -0
  242. package/src/types/data-structures/linked-list/singly-linked-list.ts +3 -0
  243. package/src/types/data-structures/linked-list/skip-linked-list.ts +1 -0
  244. package/src/types/data-structures/matrix/index.ts +2 -0
  245. package/src/types/data-structures/matrix/matrix.ts +7 -0
  246. package/src/types/data-structures/matrix/navigator.ts +14 -0
  247. package/src/types/data-structures/priority-queue/index.ts +3 -0
  248. package/src/types/data-structures/priority-queue/max-priority-queue.ts +1 -0
  249. package/src/types/data-structures/priority-queue/min-priority-queue.ts +1 -0
  250. package/src/types/data-structures/priority-queue/priority-queue.ts +3 -0
  251. package/src/types/data-structures/queue/deque.ts +5 -0
  252. package/src/types/data-structures/queue/index.ts +2 -0
  253. package/src/types/data-structures/queue/queue.ts +5 -0
  254. package/src/types/data-structures/stack/index.ts +1 -0
  255. package/src/types/data-structures/stack/stack.ts +3 -0
  256. package/src/types/data-structures/tree/index.ts +1 -0
  257. package/src/types/data-structures/tree/tree.ts +1 -0
  258. package/src/types/data-structures/trie/index.ts +1 -0
  259. package/src/types/data-structures/trie/trie.ts +3 -0
  260. package/src/types/index.ts +3 -0
  261. package/src/types/utils/index.ts +2 -0
  262. package/src/types/utils/utils.ts +33 -0
  263. package/src/types/utils/validate-type.ts +35 -0
  264. package/src/utils/index.ts +2 -0
  265. package/src/utils/number.ts +22 -0
  266. package/src/utils/utils.ts +350 -0
  267. package/test/index.test.ts +111 -0
  268. package/tsconfig.base.json +23 -0
  269. package/tsconfig.json +12 -0
  270. package/tsconfig.test.json +8 -0
  271. package/tsconfig.types.json +15 -0
  272. package/tsup.config.js +28 -0
  273. package/tsup.node.config.js +71 -0
@@ -0,0 +1,1020 @@
1
+ /**
2
+ * data-structure-typed
3
+ *
4
+ * @author Pablo Zeng
5
+ * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>
6
+ * @license MIT License
7
+ */
8
+
9
+ import type { Comparator, DFSOrderPattern, ElementCallback, HeapOptions } from '../../types';
10
+ import { IterableElementBase } from '../base';
11
+
12
+ /**
13
+ * Binary heap with pluggable comparator; supports fast insertion and removal of the top element.
14
+ * @remarks Time O(1), Space O(1)
15
+ * @template E
16
+ * @template R
17
+ * 1. Complete Binary Tree: Heaps are typically complete binary trees, meaning every level is fully filled except possibly for the last level, which has nodes as far left as possible.
18
+ * 2. Heap Properties: Each node in a heap follows a specific order property, which varies depending on the type of heap:
19
+ * Max Heap: The value of each parent node is greater than or equal to the value of its children.
20
+ * Min Heap: The value of each parent node is less than or equal to the value of its children.
21
+ * 3. Root Node Access: In a heap, the largest element (in a max heap) or the smallest element (in a min heap) is always at the root of the tree.
22
+ * 4. Efficient Insertion and Deletion: Due to its structure, a heap allows for insertion and deletion operations in logarithmic time (O(log n)).
23
+ * 5. Managing Dynamic Data Sets: Heaps effectively manage dynamic data sets, especially when frequent access to the largest or smallest elements is required.
24
+ * 6. Non-linear Search: While a heap allows rapid access to its largest or smallest element, it is less efficient for other operations, such as searching for a specific element, as it is not designed for these tasks.
25
+ * 7. Efficient Sorting Algorithms: For example, heap sort. Heap sort uses the properties of a heap to sort elements.
26
+ * 8. Graph Algorithms: Such as Dijkstra's shortest path algorithm and Prime's minimum-spanning tree algorithm, which use heaps to improve performance.
27
+ * @example
28
+ * // basic Heap creation and add operation
29
+ * // Create a min heap (default)
30
+ * const minHeap = new Heap([5, 3, 7, 1, 9, 2]);
31
+ *
32
+ * // Verify size
33
+ * console.log(minHeap.size); // 6;
34
+ *
35
+ * // Add new element
36
+ * minHeap.add(4);
37
+ * console.log(minHeap.size); // 7;
38
+ *
39
+ * // Min heap property: smallest element at root
40
+ * const min = minHeap.peek();
41
+ * console.log(min); // 1;
42
+ * @example
43
+ * // Heap with custom comparator (MaxHeap behavior)
44
+ * interface Task {
45
+ * id: number;
46
+ * priority: number;
47
+ * name: string;
48
+ * }
49
+ *
50
+ * // Custom comparator for max heap behavior (higher priority first)
51
+ * const tasks: Task[] = [
52
+ * { id: 1, priority: 5, name: 'Email' },
53
+ * { id: 2, priority: 3, name: 'Chat' },
54
+ * { id: 3, priority: 8, name: 'Alert' }
55
+ * ];
56
+ *
57
+ * const maxHeap = new Heap(tasks, {
58
+ * comparator: (a: Task, b: Task) => b.priority - a.priority
59
+ * });
60
+ *
61
+ * console.log(maxHeap.size); // 3;
62
+ *
63
+ * // Peek returns highest priority task
64
+ * const topTask = maxHeap.peek();
65
+ * console.log(topTask?.priority); // 8;
66
+ * console.log(topTask?.name); // 'Alert';
67
+ * @example
68
+ * // Heap for event processing with priority
69
+ * interface Event {
70
+ * id: number;
71
+ * type: 'critical' | 'warning' | 'info';
72
+ * timestamp: number;
73
+ * message: string;
74
+ * }
75
+ *
76
+ * // Custom priority: critical > warning > info
77
+ * const priorityMap = { critical: 3, warning: 2, info: 1 };
78
+ *
79
+ * const eventHeap = new Heap<Event>([], {
80
+ * comparator: (a: Event, b: Event) => {
81
+ * const priorityA = priorityMap[a.type];
82
+ * const priorityB = priorityMap[b.type];
83
+ * return priorityB - priorityA; // Higher priority first
84
+ * }
85
+ * });
86
+ *
87
+ * // Add events in random order
88
+ * eventHeap.add({ id: 1, type: 'info', timestamp: 100, message: 'User logged in' });
89
+ * eventHeap.add({ id: 2, type: 'critical', timestamp: 101, message: 'Server down' });
90
+ * eventHeap.add({ id: 3, type: 'warning', timestamp: 102, message: 'High memory' });
91
+ * eventHeap.add({ id: 4, type: 'info', timestamp: 103, message: 'Cache cleared' });
92
+ * eventHeap.add({ id: 5, type: 'critical', timestamp: 104, message: 'Database error' });
93
+ *
94
+ * console.log(eventHeap.size); // 5;
95
+ *
96
+ * // Process events by priority (critical first)
97
+ * const processedOrder: Event[] = [];
98
+ * while (eventHeap.size > 0) {
99
+ * const event = eventHeap.poll();
100
+ * if (event) {
101
+ * processedOrder.push(event);
102
+ * }
103
+ * }
104
+ *
105
+ * // Verify critical events came first
106
+ * console.log(processedOrder[0].type); // 'critical';
107
+ * console.log(processedOrder[1].type); // 'critical';
108
+ * console.log(processedOrder[2].type); // 'warning';
109
+ * console.log(processedOrder[3].type); // 'info';
110
+ * console.log(processedOrder[4].type); // 'info';
111
+ *
112
+ * // Verify O(log n) operations
113
+ * const newHeap = new Heap<number>([5, 3, 7, 1]);
114
+ *
115
+ * // Add - O(log n)
116
+ * newHeap.add(2);
117
+ * console.log(newHeap.size); // 5;
118
+ *
119
+ * // Poll - O(log n)
120
+ * const removed = newHeap.poll();
121
+ * console.log(removed); // 1;
122
+ *
123
+ * // Peek - O(1)
124
+ * const top = newHeap.peek();
125
+ * console.log(top); // 2;
126
+ * @example
127
+ * // Use Heap to solve top k problems
128
+ * function topKElements(arr: number[], k: number): number[] {
129
+ * const heap = new Heap<number>([], { comparator: (a, b) => b - a }); // Max heap
130
+ * arr.forEach(num => {
131
+ * heap.add(num);
132
+ * if (heap.size > k) heap.poll(); // Keep the heap size at K
133
+ * });
134
+ * return heap.toArray();
135
+ * }
136
+ *
137
+ * const numbers = [10, 30, 20, 5, 15, 25];
138
+ * console.log(topKElements(numbers, 3)); // [15, 10, 5];
139
+ * @example
140
+ * // Use Heap to dynamically maintain the median
141
+ * class MedianFinder {
142
+ * private low: MaxHeap<number>; // Max heap, stores the smaller half
143
+ * private high: MinHeap<number>; // Min heap, stores the larger half
144
+ *
145
+ * constructor() {
146
+ * this.low = new MaxHeap<number>([]);
147
+ * this.high = new MinHeap<number>([]);
148
+ * }
149
+ *
150
+ * addNum(num: number): void {
151
+ * if (this.low.isEmpty() || num <= this.low.peek()!) this.low.add(num);
152
+ * else this.high.add(num);
153
+ *
154
+ * // Balance heaps
155
+ * if (this.low.size > this.high.size + 1) this.high.add(this.low.poll()!);
156
+ * else if (this.high.size > this.low.size) this.low.add(this.high.poll()!);
157
+ * }
158
+ *
159
+ * findMedian(): number {
160
+ * if (this.low.size === this.high.size) return (this.low.peek()! + this.high.peek()!) / 2;
161
+ * return this.low.peek()!;
162
+ * }
163
+ * }
164
+ *
165
+ * const medianFinder = new MedianFinder();
166
+ * medianFinder.addNum(10);
167
+ * console.log(medianFinder.findMedian()); // 10;
168
+ * medianFinder.addNum(20);
169
+ * console.log(medianFinder.findMedian()); // 15;
170
+ * medianFinder.addNum(30);
171
+ * console.log(medianFinder.findMedian()); // 20;
172
+ * medianFinder.addNum(40);
173
+ * console.log(medianFinder.findMedian()); // 25;
174
+ * medianFinder.addNum(50);
175
+ * console.log(medianFinder.findMedian()); // 30;
176
+ * @example
177
+ * // Use Heap for load balancing
178
+ * function loadBalance(requests: number[], servers: number): number[] {
179
+ * const serverHeap = new Heap<{ id: number; load: number }>([], { comparator: (a, b) => a.load - b.load }); // min heap
180
+ * const serverLoads = new Array(servers).fill(0);
181
+ *
182
+ * for (let i = 0; i < servers; i++) {
183
+ * serverHeap.add({ id: i, load: 0 });
184
+ * }
185
+ *
186
+ * requests.forEach(req => {
187
+ * const server = serverHeap.poll()!;
188
+ * serverLoads[server.id] += req;
189
+ * server.load += req;
190
+ * serverHeap.add(server); // The server after updating the load is re-entered into the heap
191
+ * });
192
+ *
193
+ * return serverLoads;
194
+ * }
195
+ *
196
+ * const requests = [5, 2, 8, 3, 7];
197
+ * console.log(loadBalance(requests, 3)); // [12, 8, 5];
198
+ * @example
199
+ * // Use Heap to schedule tasks
200
+ * type Task = [string, number];
201
+ *
202
+ * function scheduleTasks(tasks: Task[], machines: number): Map<number, Task[]> {
203
+ * const machineHeap = new Heap<{ id: number; load: number }>([], { comparator: (a, b) => a.load - b.load }); // Min heap
204
+ * const allocation = new Map<number, Task[]>();
205
+ *
206
+ * // Initialize the load on each machine
207
+ * for (let i = 0; i < machines; i++) {
208
+ * machineHeap.add({ id: i, load: 0 });
209
+ * allocation.set(i, []);
210
+ * }
211
+ *
212
+ * // Assign tasks
213
+ * tasks.forEach(([task, load]) => {
214
+ * const machine = machineHeap.poll()!;
215
+ * allocation.get(machine.id)!.push([task, load]);
216
+ * machine.load += load;
217
+ * machineHeap.add(machine); // The machine after updating the load is re-entered into the heap
218
+ * });
219
+ *
220
+ * return allocation;
221
+ * }
222
+ *
223
+ * const tasks: Task[] = [
224
+ * ['Task1', 3],
225
+ * ['Task2', 1],
226
+ * ['Task3', 2],
227
+ * ['Task4', 5],
228
+ * ['Task5', 4]
229
+ * ];
230
+ * const expectedMap = new Map<number, Task[]>();
231
+ * expectedMap.set(0, [
232
+ * ['Task1', 3],
233
+ * ['Task4', 5]
234
+ * ]);
235
+ * expectedMap.set(1, [
236
+ * ['Task2', 1],
237
+ * ['Task3', 2],
238
+ * ['Task5', 4]
239
+ * ]);
240
+ * console.log(scheduleTasks(tasks, 2)); // expectedMap;
241
+ */
242
+ export class Heap<E = any, R = any> extends IterableElementBase<E, R> {
243
+ protected _equals: (a: E, b: E) => boolean = Object.is;
244
+
245
+ /**
246
+ * Create a Heap and optionally bulk-insert elements.
247
+ * @remarks Time O(N), Space O(N)
248
+ * @param [elements] - Iterable of elements (or raw values if toElementFn is set).
249
+ * @param [options] - Options such as comparator and toElementFn.
250
+ * @returns New Heap instance.
251
+ */
252
+
253
+ constructor(elements: Iterable<E | R> = [], options?: HeapOptions<E, R>) {
254
+ super(options);
255
+
256
+ if (options) {
257
+ const { comparator } = options;
258
+ if (comparator) this._comparator = comparator;
259
+ }
260
+
261
+ this.addMany(elements as Iterable<E | R>);
262
+ }
263
+
264
+ protected _elements: E[] = [];
265
+
266
+ /**
267
+ * Get the backing array of the heap.
268
+ * @remarks Time O(1), Space O(1)
269
+ * @returns Internal elements array.
270
+ */
271
+
272
+ get elements(): E[] {
273
+ return this._elements;
274
+ }
275
+
276
+ /**
277
+ * Get the number of elements.
278
+ * @remarks Time O(1), Space O(1)
279
+ * @returns Heap size.
280
+ */
281
+
282
+ get size(): number {
283
+ return this.elements.length;
284
+ }
285
+
286
+ /**
287
+ * Get the last leaf element.
288
+ * @remarks Time O(1), Space O(1)
289
+ * @returns Last element or undefined.
290
+ */
291
+
292
+ get leaf(): E | undefined {
293
+ return this.elements[this.size - 1] ?? undefined;
294
+ }
295
+
296
+ /**
297
+ * Create a heap of the same class from an iterable.
298
+ * @remarks Time O(N), Space O(N)
299
+ * @template T
300
+ * @template R
301
+ * @template S
302
+ * @param [elements] - Iterable of elements or raw records.
303
+ * @param [options] - Heap options including comparator.
304
+ * @returns A new heap instance of this class.
305
+ */
306
+
307
+ static from<T, R = any, S extends Heap<T, R> = Heap<T, R>>(
308
+ this: new (elements?: Iterable<T | R>, options?: HeapOptions<T, R>) => S,
309
+ elements?: Iterable<T | R>,
310
+ options?: HeapOptions<T, R>
311
+ ): S {
312
+ return new this(elements, options);
313
+ }
314
+
315
+ /**
316
+ * Build a Heap from an iterable in linear time given a comparator.
317
+ * @remarks Time O(N), Space O(N)
318
+ * @template EE
319
+ * @template RR
320
+ * @param elements - Iterable of elements.
321
+ * @param options - Heap options including comparator.
322
+ * @returns A new Heap built from elements.
323
+ */
324
+
325
+ static heapify<EE = any, RR = any>(elements: Iterable<EE>, options: HeapOptions<EE, RR>): Heap<EE, RR> {
326
+ return new Heap<EE, RR>(elements, options);
327
+ }
328
+
329
+ /**
330
+ * Insert an element.
331
+ * @remarks Time O(1) amortized, Space O(1)
332
+ * @param element - Element to insert.
333
+ * @returns True.
334
+ */
335
+
336
+ add(element: E): boolean {
337
+ this._elements.push(element);
338
+ return this._bubbleUp(this.elements.length - 1);
339
+ }
340
+
341
+ /**
342
+ * Insert many elements from an iterable.
343
+ * @remarks Time O(N log N), Space O(1)
344
+ * @param elements - Iterable of elements or raw values.
345
+ * @returns Array of per-element success flags.
346
+ */
347
+
348
+ addMany(elements: Iterable<E | R>): boolean[] {
349
+ const flags: boolean[] = [];
350
+ for (const el of elements) {
351
+ if (this.toElementFn) {
352
+ const ok = this.add(this.toElementFn(el as R));
353
+ flags.push(ok);
354
+ } else {
355
+ const ok = this.add(el as E);
356
+ flags.push(ok);
357
+ }
358
+ }
359
+ return flags;
360
+ }
361
+
362
+ /**
363
+ * Remove and return the top element.
364
+ * @remarks Time O(log N), Space O(1)
365
+ * @returns Top element or undefined.
366
+ */
367
+
368
+ poll(): E | undefined {
369
+ if (this.elements.length === 0) return;
370
+ const value = this.elements[0];
371
+ const last = this.elements.pop()!;
372
+ if (this.elements.length) {
373
+ this.elements[0] = last;
374
+ this._sinkDown(0, this.elements.length >> 1);
375
+ }
376
+ return value;
377
+ }
378
+
379
+ /**
380
+ * Get the current top element without removing it.
381
+ * @remarks Time O(1), Space O(1)
382
+ * @returns Top element or undefined.
383
+ */
384
+
385
+ peek(): E | undefined {
386
+ return this.elements[0];
387
+ }
388
+
389
+ /**
390
+ * Check whether the heap is empty.
391
+ * @remarks Time O(1), Space O(1)
392
+ * @returns True if size is 0.
393
+ */
394
+
395
+ isEmpty(): boolean {
396
+ return this.size === 0;
397
+ }
398
+
399
+ /**
400
+ * Remove all elements.
401
+ * @remarks Time O(1), Space O(1)
402
+ * @returns void
403
+ */
404
+
405
+ clear(): void {
406
+ this._elements = [];
407
+ }
408
+
409
+ /**
410
+ * Replace the backing array and rebuild the heap.
411
+ * @remarks Time O(N), Space O(N)
412
+ * @param elements - Iterable used to refill the heap.
413
+ * @returns Array of per-node results from fixing steps.
414
+ */
415
+
416
+ refill(elements: Iterable<E>): boolean[] {
417
+ this._elements = Array.from(elements);
418
+ return this.fix();
419
+ }
420
+
421
+ /**
422
+ * Check if an equal element exists in the heap.
423
+ * @remarks Time O(N), Space O(1)
424
+ * @param element - Element to search for.
425
+ * @returns True if found.
426
+ */
427
+
428
+ override has(element: E): boolean {
429
+ for (const el of this.elements) if (this._equals(el, element)) return true;
430
+ return false;
431
+ }
432
+
433
+ /**
434
+ * Delete one occurrence of an element.
435
+ * @remarks Time O(N), Space O(1)
436
+ * @param element - Element to delete.
437
+ * @returns True if an element was removed.
438
+ */
439
+
440
+ delete(element: E): boolean {
441
+ let index = -1;
442
+ for (let i = 0; i < this.elements.length; i++) {
443
+ if (this._equals(this.elements[i], element)) {
444
+ index = i;
445
+ break;
446
+ }
447
+ }
448
+ if (index < 0) return false;
449
+ if (index === 0) {
450
+ this.poll();
451
+ } else if (index === this.elements.length - 1) {
452
+ this.elements.pop();
453
+ } else {
454
+ this.elements.splice(index, 1, this.elements.pop()!);
455
+ this._bubbleUp(index);
456
+ this._sinkDown(index, this.elements.length >> 1);
457
+ }
458
+ return true;
459
+ }
460
+
461
+ /**
462
+ * Delete the first element that matches a predicate.
463
+ * @remarks Time O(N), Space O(1)
464
+ * @param predicate - Function (element, index, heap) → boolean.
465
+ * @returns True if an element was removed.
466
+ */
467
+
468
+ deleteBy(predicate: (element: E, index: number, heap: this) => boolean): boolean {
469
+ let idx = -1;
470
+ for (let i = 0; i < this.elements.length; i++) {
471
+ if (predicate(this.elements[i], i, this)) {
472
+ idx = i;
473
+ break;
474
+ }
475
+ }
476
+ if (idx < 0) return false;
477
+ if (idx === 0) {
478
+ this.poll();
479
+ } else if (idx === this.elements.length - 1) {
480
+ this.elements.pop();
481
+ } else {
482
+ this.elements.splice(idx, 1, this.elements.pop()!);
483
+ this._bubbleUp(idx);
484
+ this._sinkDown(idx, this.elements.length >> 1);
485
+ }
486
+ return true;
487
+ }
488
+
489
+ /**
490
+ * Set the equality comparator used by has/delete operations.
491
+ * @remarks Time O(1), Space O(1)
492
+ * @param equals - Equality predicate (a, b) → boolean.
493
+ * @returns This heap.
494
+ */
495
+
496
+ setEquality(equals: (a: E, b: E) => boolean): this {
497
+ this._equals = equals;
498
+ return this;
499
+ }
500
+
501
+ /**
502
+ * Traverse the binary heap as a complete binary tree and collect elements.
503
+ * @remarks Time O(N), Space O(H)
504
+ * @param [order] - Traversal order: 'PRE' | 'IN' | 'POST'.
505
+ * @returns Array of visited elements.
506
+ */
507
+
508
+ dfs(order: DFSOrderPattern = 'PRE'): E[] {
509
+ const result: E[] = [];
510
+ const _dfs = (index: number) => {
511
+ const left = 2 * index + 1,
512
+ right = left + 1;
513
+ if (index < this.size) {
514
+ if (order === 'IN') {
515
+ _dfs(left);
516
+ result.push(this.elements[index]);
517
+ _dfs(right);
518
+ } else if (order === 'PRE') {
519
+ result.push(this.elements[index]);
520
+ _dfs(left);
521
+ _dfs(right);
522
+ } else if (order === 'POST') {
523
+ _dfs(left);
524
+ _dfs(right);
525
+ result.push(this.elements[index]);
526
+ }
527
+ }
528
+ };
529
+ _dfs(0);
530
+ return result;
531
+ }
532
+
533
+ /**
534
+ * Restore heap order bottom-up (heapify in-place).
535
+ * @remarks Time O(N), Space O(1)
536
+ * @returns Array of per-node results from fixing steps.
537
+ */
538
+
539
+ fix(): boolean[] {
540
+ const results: boolean[] = [];
541
+ for (let i = Math.floor(this.size / 2) - 1; i >= 0; i--) {
542
+ results.push(this._sinkDown(i, this.elements.length >> 1));
543
+ }
544
+ return results;
545
+ }
546
+
547
+ /**
548
+ * Return all elements in ascending order by repeatedly polling.
549
+ * @remarks Time O(N log N), Space O(N)
550
+ * @returns Sorted array of elements.
551
+ */
552
+
553
+ sort(): E[] {
554
+ const visited: E[] = [];
555
+ const cloned = this._createInstance();
556
+ for (const x of this.elements) cloned.add(x);
557
+ while (!cloned.isEmpty()) {
558
+ const top = cloned.poll();
559
+ if (top !== undefined) visited.push(top);
560
+ }
561
+ return visited;
562
+ }
563
+
564
+ /**
565
+ * Deep clone this heap.
566
+ * @remarks Time O(N), Space O(N)
567
+ * @returns A new heap with the same elements.
568
+ */
569
+
570
+ clone(): this {
571
+ const next = this._createInstance();
572
+ for (const x of this.elements) next.add(x);
573
+ return next;
574
+ }
575
+
576
+ /**
577
+ * Filter elements into a new heap of the same class.
578
+ * @remarks Time O(N log N), Space O(N)
579
+ * @param callback - Predicate (element, index, heap) → boolean to keep element.
580
+ * @param [thisArg] - Value for `this` inside the callback.
581
+ * @returns A new heap with the kept elements.
582
+ */
583
+
584
+ filter(callback: ElementCallback<E, R, boolean>, thisArg?: unknown): this {
585
+ const out = this._createInstance();
586
+ let i = 0;
587
+ for (const x of this) {
588
+ if (thisArg === undefined ? callback(x, i++, this) : callback.call(thisArg, x, i++, this)) {
589
+ out.add(x);
590
+ } else {
591
+ i++;
592
+ }
593
+ }
594
+ return out;
595
+ }
596
+
597
+ /**
598
+ * Map elements into a new heap of possibly different element type.
599
+ * @remarks Time O(N log N), Space O(N)
600
+ * @template EM
601
+ * @template RM
602
+ * @param callback - Mapping function (element, index, heap) → newElement.
603
+ * @param options - Options for the output heap, including comparator for EM.
604
+ * @param [thisArg] - Value for `this` inside the callback.
605
+ * @returns A new heap with mapped elements.
606
+ */
607
+
608
+ map<EM, RM>(
609
+ callback: ElementCallback<E, R, EM>,
610
+ options: HeapOptions<EM, RM> & { comparator: Comparator<EM> },
611
+ thisArg?: unknown
612
+ ): Heap<EM, RM> {
613
+ const { comparator, toElementFn, ...rest } = options ?? {};
614
+ if (!comparator) throw new TypeError('Heap.map requires options.comparator for EM');
615
+ const out = this._createLike<EM, RM>([], { ...rest, comparator, toElementFn });
616
+ let i = 0;
617
+ for (const x of this) {
618
+ const v = thisArg === undefined ? callback(x, i++, this) : callback.call(thisArg, x, i++, this);
619
+ out.add(v);
620
+ }
621
+ return out;
622
+ }
623
+
624
+ /**
625
+ * Map elements into a new heap of the same element type.
626
+ * @remarks Time O(N log N), Space O(N)
627
+ * @param callback - Mapping function (element, index, heap) → element.
628
+ * @param [thisArg] - Value for `this` inside the callback.
629
+ * @returns A new heap with mapped elements.
630
+ */
631
+
632
+ mapSame(callback: ElementCallback<E, R, E>, thisArg?: unknown): this {
633
+ const out = this._createInstance();
634
+ let i = 0;
635
+ for (const x of this) {
636
+ const v = thisArg === undefined ? callback(x, i++, this) : callback.call(thisArg, x, i++, this);
637
+ out.add(v);
638
+ }
639
+ return out;
640
+ }
641
+
642
+ protected _DEFAULT_COMPARATOR = (a: E, b: E): number => {
643
+ if (typeof a === 'object' || typeof b === 'object') {
644
+ throw TypeError('When comparing object types, define a custom comparator in options.');
645
+ }
646
+ if ((a as unknown as number) > (b as unknown as number)) return 1;
647
+ if ((a as unknown as number) < (b as unknown as number)) return -1;
648
+ return 0;
649
+ };
650
+
651
+ protected _comparator: Comparator<E> = this._DEFAULT_COMPARATOR; /**
652
+ * Get the comparator used to order elements.
653
+ * @remarks Time O(1), Space O(1)
654
+ * @returns Comparator function.
655
+ */
656
+ /**
657
+ * Get the comparator used to order elements.
658
+ * @remarks Time O(1), Space O(1)
659
+ * @returns Comparator function.
660
+ */
661
+
662
+ get comparator() {
663
+ return this._comparator;
664
+ }
665
+
666
+ protected *_getIterator(): IterableIterator<E> {
667
+ for (const element of this.elements) yield element;
668
+ }
669
+
670
+ protected _bubbleUp(index: number): boolean {
671
+ const element = this.elements[index];
672
+ while (index > 0) {
673
+ const parent = (index - 1) >> 1;
674
+ const parentItem = this.elements[parent];
675
+ if (this.comparator(parentItem, element) <= 0) break;
676
+ this.elements[index] = parentItem;
677
+ index = parent;
678
+ }
679
+ this.elements[index] = element;
680
+ return true;
681
+ }
682
+
683
+ protected _sinkDown(index: number, halfLength: number): boolean {
684
+ const element = this.elements[index];
685
+ while (index < halfLength) {
686
+ let left = (index << 1) | 1;
687
+ const right = left + 1;
688
+ let minItem = this.elements[left];
689
+ if (right < this.elements.length && this.comparator(minItem, this.elements[right]) > 0) {
690
+ left = right;
691
+ minItem = this.elements[right];
692
+ }
693
+ if (this.comparator(minItem, element) >= 0) break;
694
+ this.elements[index] = minItem;
695
+ index = left;
696
+ }
697
+ this.elements[index] = element;
698
+ return true;
699
+ }
700
+
701
+ /**
702
+ * (Protected) Create an empty instance of the same concrete class.
703
+ * @remarks Time O(1), Space O(1)
704
+ * @param [options] - Options to override comparator or toElementFn.
705
+ * @returns A like-kind empty heap instance.
706
+ */
707
+
708
+ protected _createInstance(options?: HeapOptions<E, R>): this {
709
+ const Ctor: any = this.constructor;
710
+ const next: any = new Ctor([], { comparator: this.comparator, toElementFn: this.toElementFn, ...(options ?? {}) });
711
+ return next as this;
712
+ }
713
+
714
+ /**
715
+ * (Protected) Create a like-kind instance seeded by elements.
716
+ * @remarks Time O(N log N), Space O(N)
717
+ * @template EM
718
+ * @template RM
719
+ * @param [elements] - Iterable of elements or raw values to seed.
720
+ * @param [options] - Options forwarded to the constructor.
721
+ * @returns A like-kind heap instance.
722
+ */
723
+
724
+ protected _createLike<EM, RM>(
725
+ elements: Iterable<EM> | Iterable<RM> = [],
726
+ options?: HeapOptions<EM, RM>
727
+ ): Heap<EM, RM> {
728
+ const Ctor: any = this.constructor;
729
+ return new Ctor(elements, options) as Heap<EM, RM>;
730
+ }
731
+
732
+ /**
733
+ * (Protected) Spawn an empty like-kind heap instance.
734
+ * @remarks Time O(1), Space O(1)
735
+ * @template EM
736
+ * @template RM
737
+ * @param [options] - Options forwarded to the constructor.
738
+ * @returns An empty like-kind heap instance.
739
+ */
740
+
741
+ protected _spawnLike<EM, RM>(options?: HeapOptions<EM, RM>): Heap<EM, RM> {
742
+ return this._createLike<EM, RM>([], options);
743
+ }
744
+ }
745
+
746
+ /**
747
+ * Node container used by FibonacciHeap.
748
+ * @remarks Time O(1), Space O(1)
749
+ * @template E
750
+ */
751
+ export class FibonacciHeapNode<E> {
752
+ element: E;
753
+ degree: number;
754
+ left?: FibonacciHeapNode<E>;
755
+ right?: FibonacciHeapNode<E>;
756
+ child?: FibonacciHeapNode<E>;
757
+ parent?: FibonacciHeapNode<E>;
758
+ marked: boolean;
759
+
760
+ constructor(element: E, degree = 0) {
761
+ this.element = element;
762
+ this.degree = degree;
763
+ this.marked = false;
764
+ }
765
+ }
766
+
767
+ /**
768
+ * Fibonacci heap (min-heap) optimized for fast merges and amortized operations.
769
+ * @remarks Time O(1), Space O(1)
770
+ * @template E
771
+ * @example examples will be generated by unit test
772
+ */
773
+ export class FibonacciHeap<E> {
774
+ /**
775
+ * Create a FibonacciHeap.
776
+ * @remarks Time O(1), Space O(1)
777
+ * @param [comparator] - Comparator to order elements (min-heap by default).
778
+ * @returns New FibonacciHeap instance.
779
+ */
780
+
781
+ constructor(comparator?: Comparator<E>) {
782
+ this.clear();
783
+ this._comparator = comparator || this._defaultComparator;
784
+ if (typeof this.comparator !== 'function') throw new Error('FibonacciHeap: comparator must be a function.');
785
+ }
786
+
787
+ protected _root?: FibonacciHeapNode<E>;
788
+
789
+ /**
790
+ * Get the circular root list head.
791
+ * @remarks Time O(1), Space O(1)
792
+ * @returns Root node or undefined.
793
+ */
794
+
795
+ get root(): FibonacciHeapNode<E> | undefined {
796
+ return this._root;
797
+ }
798
+
799
+ protected _size = 0;
800
+ get size(): number {
801
+ return this._size;
802
+ }
803
+
804
+ protected _min?: FibonacciHeapNode<E>;
805
+
806
+ /**
807
+ * Get the current minimum node.
808
+ * @remarks Time O(1), Space O(1)
809
+ * @returns Min node or undefined.
810
+ */
811
+
812
+ get min(): FibonacciHeapNode<E> | undefined {
813
+ return this._min;
814
+ }
815
+
816
+ protected _comparator: Comparator<E>;
817
+ get comparator(): Comparator<E> {
818
+ return this._comparator;
819
+ }
820
+
821
+ clear(): void {
822
+ this._root = undefined;
823
+ this._min = undefined;
824
+ this._size = 0;
825
+ }
826
+
827
+ add(element: E): boolean {
828
+ this.push(element);
829
+ return true;
830
+ }
831
+
832
+ /**
833
+ * Push an element into the root list.
834
+ * @remarks Time O(1) amortized, Space O(1)
835
+ * @param element - Element to insert.
836
+ * @returns This heap.
837
+ */
838
+
839
+ push(element: E): this {
840
+ const node = this.createNode(element);
841
+ node.left = node;
842
+ node.right = node;
843
+ this.mergeWithRoot(node);
844
+ if (!this.min || this.comparator(node.element, this.min.element) <= 0) this._min = node;
845
+ this._size++;
846
+ return this;
847
+ }
848
+
849
+ peek(): E | undefined {
850
+ return this.min ? this.min.element : undefined;
851
+ }
852
+
853
+ /**
854
+ * Collect nodes from a circular doubly linked list starting at head.
855
+ * @remarks Time O(K), Space O(K)
856
+ * @param [head] - Start node of the circular list.
857
+ * @returns Array of nodes from the list.
858
+ */
859
+
860
+ consumeLinkedList(head?: FibonacciHeapNode<E>): FibonacciHeapNode<E>[] {
861
+ const elements: FibonacciHeapNode<E>[] = [];
862
+ if (!head) return elements;
863
+ let node: FibonacciHeapNode<E> | undefined = head;
864
+ let started = false;
865
+ while (true) {
866
+ if (node === head && started) break;
867
+ else if (node === head) started = true;
868
+ elements.push(node!);
869
+ node = node!.right;
870
+ }
871
+ return elements;
872
+ }
873
+
874
+ /**
875
+ * Insert a node into a parent's child list (circular).
876
+ * @remarks Time O(1), Space O(1)
877
+ * @param parent - Parent node.
878
+ * @param node - Child node to insert.
879
+ * @returns void
880
+ */
881
+
882
+ mergeWithChild(parent: FibonacciHeapNode<E>, node: FibonacciHeapNode<E>): void {
883
+ if (!parent.child) parent.child = node;
884
+ else {
885
+ node.right = parent.child.right;
886
+ node.left = parent.child;
887
+ parent.child.right!.left = node;
888
+ parent.child.right = node;
889
+ }
890
+ }
891
+
892
+ poll(): E | undefined {
893
+ return this.pop();
894
+ }
895
+
896
+ /**
897
+ * Remove and return the minimum element, consolidating the root list.
898
+ * @remarks Time O(log N) amortized, Space O(1)
899
+ * @returns Minimum element or undefined.
900
+ */
901
+
902
+ pop(): E | undefined {
903
+ if (this._size === 0) return undefined;
904
+ const z = this.min!;
905
+ if (z.child) {
906
+ const elements = this.consumeLinkedList(z.child);
907
+ for (const node of elements) {
908
+ this.mergeWithRoot(node);
909
+ node.parent = undefined;
910
+ }
911
+ }
912
+ this.removeFromRoot(z);
913
+ if (z === z.right) {
914
+ this._min = undefined;
915
+ this._root = undefined;
916
+ } else {
917
+ this._min = z.right;
918
+ this._consolidate();
919
+ }
920
+ this._size--;
921
+ return z.element;
922
+ }
923
+
924
+ /**
925
+ * Meld another heap into this heap.
926
+ * @remarks Time O(1), Space O(1)
927
+ * @param heapToMerge - Another FibonacciHeap to meld into this one.
928
+ * @returns void
929
+ */
930
+
931
+ merge(heapToMerge: FibonacciHeap<E>): void {
932
+ if (heapToMerge.size === 0) return;
933
+ if (this.root && heapToMerge.root) {
934
+ const thisRoot = this.root,
935
+ otherRoot = heapToMerge.root;
936
+ const thisRootRight = thisRoot.right!,
937
+ otherRootLeft = otherRoot.left!;
938
+ thisRoot.right = otherRoot;
939
+ otherRoot.left = thisRoot;
940
+ thisRootRight.left = otherRootLeft;
941
+ otherRootLeft.right = thisRootRight;
942
+ } else if (!this.root && heapToMerge.root) {
943
+ this._root = heapToMerge.root;
944
+ }
945
+ if (!this.min || (heapToMerge.min && this.comparator(heapToMerge.min.element, this.min.element) < 0)) {
946
+ this._min = heapToMerge.min;
947
+ }
948
+ this._size += heapToMerge.size;
949
+ heapToMerge.clear();
950
+ }
951
+
952
+ createNode(element: E): FibonacciHeapNode<E> {
953
+ return new FibonacciHeapNode<E>(element);
954
+ }
955
+
956
+ isEmpty(): boolean {
957
+ return this._size === 0;
958
+ }
959
+
960
+ protected _defaultComparator(a: E, b: E): number {
961
+ if (a < b) return -1;
962
+ if (a > b) return 1;
963
+ return 0;
964
+ }
965
+
966
+ protected mergeWithRoot(node: FibonacciHeapNode<E>): void {
967
+ if (!this.root) this._root = node;
968
+ else {
969
+ node.right = this.root.right;
970
+ node.left = this.root;
971
+ this.root.right!.left = node;
972
+ this.root.right = node;
973
+ }
974
+ }
975
+
976
+ protected removeFromRoot(node: FibonacciHeapNode<E>): void {
977
+ if (this.root === node) this._root = node.right;
978
+ if (node.left) node.left.right = node.right;
979
+ if (node.right) node.right.left = node.left;
980
+ }
981
+
982
+ protected _link(y: FibonacciHeapNode<E>, x: FibonacciHeapNode<E>): void {
983
+ this.removeFromRoot(y);
984
+ y.left = y;
985
+ y.right = y;
986
+ this.mergeWithChild(x, y);
987
+ x.degree++;
988
+ y.parent = x;
989
+ }
990
+
991
+ protected _consolidate(): void {
992
+ const A: (FibonacciHeapNode<E> | undefined)[] = new Array(this._size);
993
+ const elements = this.consumeLinkedList(this.root);
994
+ let x: FibonacciHeapNode<E> | undefined,
995
+ y: FibonacciHeapNode<E> | undefined,
996
+ d: number,
997
+ t: FibonacciHeapNode<E> | undefined;
998
+
999
+ for (const node of elements) {
1000
+ x = node;
1001
+ d = x.degree;
1002
+ while (A[d]) {
1003
+ y = A[d] as FibonacciHeapNode<E>;
1004
+ if (this.comparator(x.element, y.element) > 0) {
1005
+ t = x;
1006
+ x = y;
1007
+ y = t;
1008
+ }
1009
+ this._link(y, x);
1010
+ A[d] = undefined;
1011
+ d++;
1012
+ }
1013
+ A[d] = x;
1014
+ }
1015
+
1016
+ for (let i = 0; i < A.length; i++) {
1017
+ if (A[i] && (!this.min || this.comparator(A[i]!.element, this.min.element) <= 0)) this._min = A[i]!;
1018
+ }
1019
+ }
1020
+ }