directed-graph-typed 2.1.0 → 2.1.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 (281) hide show
  1. package/dist/cjs/index.cjs +2798 -0
  2. package/dist/cjs/index.cjs.map +1 -0
  3. package/dist/esm/index.mjs +2789 -0
  4. package/dist/esm/index.mjs.map +1 -0
  5. package/dist/types/data-structures/base/index.d.ts +2 -1
  6. package/dist/types/data-structures/binary-tree/avl-tree-counter.d.ts +182 -2
  7. package/dist/types/data-structures/binary-tree/avl-tree-multi-map.d.ts +135 -2
  8. package/dist/types/data-structures/binary-tree/avl-tree.d.ts +291 -2
  9. package/dist/types/data-structures/binary-tree/binary-indexed-tree.d.ts +174 -1
  10. package/dist/types/data-structures/binary-tree/binary-tree.d.ts +754 -29
  11. package/dist/types/data-structures/binary-tree/bst.d.ts +413 -12
  12. package/dist/types/data-structures/binary-tree/index.d.ts +3 -2
  13. package/dist/types/data-structures/binary-tree/red-black-tree.d.ts +208 -3
  14. package/dist/types/data-structures/binary-tree/segment-tree.d.ts +160 -1
  15. package/dist/types/data-structures/binary-tree/tree-counter.d.ts +190 -2
  16. package/dist/types/data-structures/binary-tree/tree-multi-map.d.ts +270 -2
  17. package/dist/types/data-structures/graph/abstract-graph.d.ts +340 -14
  18. package/dist/types/data-structures/graph/directed-graph.d.ts +207 -1
  19. package/dist/types/data-structures/graph/index.d.ts +2 -1
  20. package/dist/types/data-structures/graph/map-graph.d.ts +78 -1
  21. package/dist/types/data-structures/graph/undirected-graph.d.ts +188 -1
  22. package/dist/types/data-structures/hash/hash-map.d.ts +345 -19
  23. package/dist/types/data-structures/hash/index.d.ts +0 -1
  24. package/dist/types/data-structures/heap/heap.d.ts +503 -5
  25. package/dist/types/data-structures/heap/index.d.ts +2 -0
  26. package/dist/types/data-structures/heap/max-heap.d.ts +32 -1
  27. package/dist/types/data-structures/heap/min-heap.d.ts +33 -1
  28. package/dist/types/data-structures/index.d.ts +7 -7
  29. package/dist/types/data-structures/linked-list/doubly-linked-list.d.ts +769 -2
  30. package/dist/types/data-structures/linked-list/singly-linked-list.d.ts +451 -2
  31. package/dist/types/data-structures/linked-list/skip-linked-list.d.ts +27 -4
  32. package/dist/types/data-structures/matrix/index.d.ts +1 -1
  33. package/dist/types/data-structures/matrix/matrix.d.ts +168 -7
  34. package/dist/types/data-structures/matrix/navigator.d.ts +54 -13
  35. package/dist/types/data-structures/priority-queue/max-priority-queue.d.ts +27 -1
  36. package/dist/types/data-structures/priority-queue/min-priority-queue.d.ts +26 -1
  37. package/dist/types/data-structures/priority-queue/priority-queue.d.ts +15 -2
  38. package/dist/types/data-structures/queue/deque.d.ts +431 -4
  39. package/dist/types/data-structures/queue/queue.d.ts +308 -4
  40. package/dist/types/data-structures/stack/stack.d.ts +306 -2
  41. package/dist/types/data-structures/tree/tree.d.ts +62 -1
  42. package/dist/types/data-structures/trie/trie.d.ts +350 -4
  43. package/dist/types/index.d.ts +13 -2
  44. package/dist/{interfaces → types/interfaces}/binary-tree.d.ts +3 -3
  45. package/dist/types/types/data-structures/base/index.d.ts +1 -0
  46. package/dist/types/types/data-structures/binary-tree/avl-tree-counter.d.ts +2 -0
  47. package/dist/types/types/data-structures/binary-tree/avl-tree-multi-map.d.ts +2 -0
  48. package/dist/types/types/data-structures/binary-tree/avl-tree.d.ts +2 -0
  49. package/dist/types/types/data-structures/binary-tree/binary-indexed-tree.d.ts +1 -0
  50. package/dist/types/types/data-structures/binary-tree/binary-tree.d.ts +29 -0
  51. package/dist/types/types/data-structures/binary-tree/bst.d.ts +12 -0
  52. package/dist/{data-structures → types/types/data-structures}/binary-tree/index.d.ts +2 -3
  53. package/dist/types/types/data-structures/binary-tree/red-black-tree.d.ts +3 -0
  54. package/dist/types/types/data-structures/binary-tree/segment-tree.d.ts +1 -0
  55. package/dist/types/types/data-structures/binary-tree/tree-counter.d.ts +2 -0
  56. package/dist/types/types/data-structures/binary-tree/tree-multi-map.d.ts +2 -0
  57. package/dist/types/types/data-structures/graph/abstract-graph.d.ts +14 -0
  58. package/dist/types/types/data-structures/graph/directed-graph.d.ts +1 -0
  59. package/dist/{data-structures → types/types/data-structures}/graph/index.d.ts +1 -2
  60. package/dist/types/types/data-structures/graph/map-graph.d.ts +1 -0
  61. package/dist/types/types/data-structures/graph/undirected-graph.d.ts +1 -0
  62. package/dist/types/types/data-structures/hash/hash-map.d.ts +19 -0
  63. package/dist/types/types/data-structures/hash/index.d.ts +2 -0
  64. package/dist/types/types/data-structures/heap/heap.d.ts +5 -0
  65. package/dist/types/types/data-structures/heap/index.d.ts +1 -0
  66. package/dist/types/types/data-structures/heap/max-heap.d.ts +1 -0
  67. package/dist/types/types/data-structures/heap/min-heap.d.ts +1 -0
  68. package/dist/types/types/data-structures/linked-list/doubly-linked-list.d.ts +2 -0
  69. package/dist/types/types/data-structures/linked-list/singly-linked-list.d.ts +2 -0
  70. package/dist/types/types/data-structures/linked-list/skip-linked-list.d.ts +4 -0
  71. package/dist/types/types/data-structures/matrix/matrix.d.ts +7 -0
  72. package/dist/types/types/data-structures/matrix/navigator.d.ts +14 -0
  73. package/dist/types/types/data-structures/priority-queue/max-priority-queue.d.ts +1 -0
  74. package/dist/types/types/data-structures/priority-queue/min-priority-queue.d.ts +1 -0
  75. package/dist/types/types/data-structures/priority-queue/priority-queue.d.ts +2 -0
  76. package/dist/types/types/data-structures/queue/deque.d.ts +4 -0
  77. package/dist/types/types/data-structures/queue/queue.d.ts +4 -0
  78. package/dist/types/types/data-structures/stack/stack.d.ts +2 -0
  79. package/dist/types/types/data-structures/tree/tree.d.ts +1 -0
  80. package/dist/types/types/data-structures/trie/trie.d.ts +4 -0
  81. package/dist/types/types/index.d.ts +3 -0
  82. package/dist/types/types/utils/index.d.ts +2 -0
  83. package/dist/types/types/utils/utils.d.ts +22 -0
  84. package/dist/types/utils/index.d.ts +1 -1
  85. package/dist/types/utils/utils.d.ts +209 -22
  86. package/dist/umd/directed-graph-typed.js +2791 -0
  87. package/dist/umd/directed-graph-typed.js.map +1 -0
  88. package/dist/umd/directed-graph-typed.min.js +9 -0
  89. package/dist/umd/directed-graph-typed.min.js.map +1 -0
  90. package/package.json +25 -5
  91. package/src/data-structures/binary-tree/avl-tree-counter.ts +8 -11
  92. package/src/data-structures/binary-tree/avl-tree-multi-map.ts +6 -11
  93. package/src/data-structures/binary-tree/avl-tree.ts +6 -8
  94. package/src/data-structures/binary-tree/binary-tree.ts +13 -15
  95. package/src/data-structures/binary-tree/bst.ts +6 -11
  96. package/src/data-structures/binary-tree/red-black-tree.ts +6 -11
  97. package/src/data-structures/binary-tree/tree-counter.ts +8 -13
  98. package/src/data-structures/binary-tree/tree-multi-map.ts +6 -11
  99. package/src/data-structures/heap/heap.ts +5 -5
  100. package/src/data-structures/linked-list/singly-linked-list.ts +2 -2
  101. package/src/interfaces/binary-tree.ts +3 -3
  102. package/tsconfig.base.json +23 -0
  103. package/tsconfig.json +8 -34
  104. package/tsconfig.test.json +8 -0
  105. package/tsconfig.types.json +15 -0
  106. package/tsup.config.js +28 -0
  107. package/tsup.node.config.js +37 -0
  108. package/dist/common/index.js +0 -28
  109. package/dist/constants/index.js +0 -8
  110. package/dist/data-structures/base/index.d.ts +0 -2
  111. package/dist/data-structures/base/index.js +0 -18
  112. package/dist/data-structures/base/iterable-element-base.js +0 -243
  113. package/dist/data-structures/base/iterable-entry-base.js +0 -183
  114. package/dist/data-structures/base/linear-base.js +0 -415
  115. package/dist/data-structures/binary-tree/avl-tree-counter.d.ts +0 -182
  116. package/dist/data-structures/binary-tree/avl-tree-counter.js +0 -374
  117. package/dist/data-structures/binary-tree/avl-tree-multi-map.d.ts +0 -135
  118. package/dist/data-structures/binary-tree/avl-tree-multi-map.js +0 -250
  119. package/dist/data-structures/binary-tree/avl-tree.d.ts +0 -291
  120. package/dist/data-structures/binary-tree/avl-tree.js +0 -611
  121. package/dist/data-structures/binary-tree/binary-indexed-tree.d.ts +0 -174
  122. package/dist/data-structures/binary-tree/binary-indexed-tree.js +0 -294
  123. package/dist/data-structures/binary-tree/binary-tree.d.ts +0 -754
  124. package/dist/data-structures/binary-tree/binary-tree.js +0 -1925
  125. package/dist/data-structures/binary-tree/bst.d.ts +0 -413
  126. package/dist/data-structures/binary-tree/bst.js +0 -903
  127. package/dist/data-structures/binary-tree/index.js +0 -26
  128. package/dist/data-structures/binary-tree/red-black-tree.d.ts +0 -208
  129. package/dist/data-structures/binary-tree/red-black-tree.js +0 -546
  130. package/dist/data-structures/binary-tree/segment-tree.d.ts +0 -160
  131. package/dist/data-structures/binary-tree/segment-tree.js +0 -297
  132. package/dist/data-structures/binary-tree/tree-counter.d.ts +0 -190
  133. package/dist/data-structures/binary-tree/tree-counter.js +0 -413
  134. package/dist/data-structures/binary-tree/tree-multi-map.d.ts +0 -270
  135. package/dist/data-structures/binary-tree/tree-multi-map.js +0 -384
  136. package/dist/data-structures/graph/abstract-graph.d.ts +0 -340
  137. package/dist/data-structures/graph/abstract-graph.js +0 -896
  138. package/dist/data-structures/graph/directed-graph.d.ts +0 -207
  139. package/dist/data-structures/graph/directed-graph.js +0 -525
  140. package/dist/data-structures/graph/index.js +0 -20
  141. package/dist/data-structures/graph/map-graph.d.ts +0 -78
  142. package/dist/data-structures/graph/map-graph.js +0 -107
  143. package/dist/data-structures/graph/undirected-graph.d.ts +0 -188
  144. package/dist/data-structures/graph/undirected-graph.js +0 -424
  145. package/dist/data-structures/hash/hash-map.d.ts +0 -345
  146. package/dist/data-structures/hash/hash-map.js +0 -692
  147. package/dist/data-structures/hash/index.d.ts +0 -1
  148. package/dist/data-structures/hash/index.js +0 -17
  149. package/dist/data-structures/heap/heap.d.ts +0 -503
  150. package/dist/data-structures/heap/heap.js +0 -901
  151. package/dist/data-structures/heap/index.d.ts +0 -3
  152. package/dist/data-structures/heap/index.js +0 -19
  153. package/dist/data-structures/heap/max-heap.d.ts +0 -32
  154. package/dist/data-structures/heap/max-heap.js +0 -40
  155. package/dist/data-structures/heap/min-heap.d.ts +0 -33
  156. package/dist/data-structures/heap/min-heap.js +0 -31
  157. package/dist/data-structures/index.js +0 -28
  158. package/dist/data-structures/linked-list/doubly-linked-list.d.ts +0 -769
  159. package/dist/data-structures/linked-list/doubly-linked-list.js +0 -1111
  160. package/dist/data-structures/linked-list/index.js +0 -19
  161. package/dist/data-structures/linked-list/singly-linked-list.d.ts +0 -451
  162. package/dist/data-structures/linked-list/singly-linked-list.js +0 -850
  163. package/dist/data-structures/linked-list/skip-linked-list.d.ts +0 -27
  164. package/dist/data-structures/linked-list/skip-linked-list.js +0 -144
  165. package/dist/data-structures/matrix/index.js +0 -18
  166. package/dist/data-structures/matrix/matrix.d.ts +0 -168
  167. package/dist/data-structures/matrix/matrix.js +0 -448
  168. package/dist/data-structures/matrix/navigator.d.ts +0 -55
  169. package/dist/data-structures/matrix/navigator.js +0 -111
  170. package/dist/data-structures/priority-queue/index.js +0 -19
  171. package/dist/data-structures/priority-queue/max-priority-queue.d.ts +0 -27
  172. package/dist/data-structures/priority-queue/max-priority-queue.js +0 -34
  173. package/dist/data-structures/priority-queue/min-priority-queue.d.ts +0 -26
  174. package/dist/data-structures/priority-queue/min-priority-queue.js +0 -24
  175. package/dist/data-structures/priority-queue/priority-queue.d.ts +0 -15
  176. package/dist/data-structures/priority-queue/priority-queue.js +0 -20
  177. package/dist/data-structures/queue/deque.d.ts +0 -431
  178. package/dist/data-structures/queue/deque.js +0 -879
  179. package/dist/data-structures/queue/index.js +0 -18
  180. package/dist/data-structures/queue/queue.d.ts +0 -308
  181. package/dist/data-structures/queue/queue.js +0 -473
  182. package/dist/data-structures/stack/index.js +0 -17
  183. package/dist/data-structures/stack/stack.d.ts +0 -306
  184. package/dist/data-structures/stack/stack.js +0 -401
  185. package/dist/data-structures/tree/index.js +0 -17
  186. package/dist/data-structures/tree/tree.d.ts +0 -62
  187. package/dist/data-structures/tree/tree.js +0 -107
  188. package/dist/data-structures/trie/index.js +0 -17
  189. package/dist/data-structures/trie/trie.d.ts +0 -350
  190. package/dist/data-structures/trie/trie.js +0 -610
  191. package/dist/index.d.ts +0 -14
  192. package/dist/index.js +0 -30
  193. package/dist/interfaces/binary-tree.js +0 -2
  194. package/dist/interfaces/doubly-linked-list.js +0 -2
  195. package/dist/interfaces/graph.js +0 -2
  196. package/dist/interfaces/heap.js +0 -2
  197. package/dist/interfaces/index.js +0 -24
  198. package/dist/interfaces/navigator.js +0 -2
  199. package/dist/interfaces/priority-queue.js +0 -2
  200. package/dist/interfaces/segment-tree.js +0 -2
  201. package/dist/interfaces/singly-linked-list.js +0 -2
  202. package/dist/types/common.js +0 -2
  203. package/dist/types/data-structures/base/base.js +0 -2
  204. package/dist/types/data-structures/base/index.js +0 -17
  205. package/dist/types/data-structures/binary-tree/avl-tree-counter.js +0 -2
  206. package/dist/types/data-structures/binary-tree/avl-tree-multi-map.js +0 -2
  207. package/dist/types/data-structures/binary-tree/avl-tree.js +0 -2
  208. package/dist/types/data-structures/binary-tree/binary-indexed-tree.js +0 -2
  209. package/dist/types/data-structures/binary-tree/binary-tree.js +0 -2
  210. package/dist/types/data-structures/binary-tree/bst.js +0 -2
  211. package/dist/types/data-structures/binary-tree/index.js +0 -25
  212. package/dist/types/data-structures/binary-tree/red-black-tree.js +0 -2
  213. package/dist/types/data-structures/binary-tree/segment-tree.js +0 -2
  214. package/dist/types/data-structures/binary-tree/tree-counter.js +0 -2
  215. package/dist/types/data-structures/binary-tree/tree-multi-map.js +0 -2
  216. package/dist/types/data-structures/graph/abstract-graph.js +0 -2
  217. package/dist/types/data-structures/graph/directed-graph.js +0 -2
  218. package/dist/types/data-structures/graph/index.js +0 -19
  219. package/dist/types/data-structures/graph/map-graph.js +0 -2
  220. package/dist/types/data-structures/graph/undirected-graph.js +0 -2
  221. package/dist/types/data-structures/hash/hash-map.js +0 -2
  222. package/dist/types/data-structures/hash/index.js +0 -17
  223. package/dist/types/data-structures/heap/heap.js +0 -2
  224. package/dist/types/data-structures/heap/index.js +0 -17
  225. package/dist/types/data-structures/heap/max-heap.js +0 -2
  226. package/dist/types/data-structures/heap/min-heap.js +0 -2
  227. package/dist/types/data-structures/index.js +0 -28
  228. package/dist/types/data-structures/linked-list/doubly-linked-list.js +0 -2
  229. package/dist/types/data-structures/linked-list/index.js +0 -19
  230. package/dist/types/data-structures/linked-list/singly-linked-list.js +0 -2
  231. package/dist/types/data-structures/linked-list/skip-linked-list.js +0 -2
  232. package/dist/types/data-structures/matrix/index.js +0 -18
  233. package/dist/types/data-structures/matrix/matrix.js +0 -2
  234. package/dist/types/data-structures/matrix/navigator.js +0 -2
  235. package/dist/types/data-structures/priority-queue/index.js +0 -19
  236. package/dist/types/data-structures/priority-queue/max-priority-queue.js +0 -2
  237. package/dist/types/data-structures/priority-queue/min-priority-queue.js +0 -2
  238. package/dist/types/data-structures/priority-queue/priority-queue.js +0 -2
  239. package/dist/types/data-structures/queue/deque.js +0 -2
  240. package/dist/types/data-structures/queue/index.js +0 -18
  241. package/dist/types/data-structures/queue/queue.js +0 -2
  242. package/dist/types/data-structures/stack/index.js +0 -17
  243. package/dist/types/data-structures/stack/stack.js +0 -2
  244. package/dist/types/data-structures/tree/index.js +0 -17
  245. package/dist/types/data-structures/tree/tree.js +0 -2
  246. package/dist/types/data-structures/trie/index.js +0 -17
  247. package/dist/types/data-structures/trie/trie.js +0 -2
  248. package/dist/types/index.js +0 -19
  249. package/dist/types/utils/index.js +0 -18
  250. package/dist/types/utils/utils.js +0 -2
  251. package/dist/types/utils/validate-type.js +0 -2
  252. package/dist/utils/index.d.ts +0 -2
  253. package/dist/utils/index.js +0 -18
  254. package/dist/utils/number.js +0 -24
  255. package/dist/utils/utils.d.ts +0 -209
  256. package/dist/utils/utils.js +0 -353
  257. package/dist/{common → types/common}/index.d.ts +0 -0
  258. package/dist/{constants → types/constants}/index.d.ts +0 -0
  259. package/dist/{data-structures → types/data-structures}/base/iterable-element-base.d.ts +0 -0
  260. package/dist/{data-structures → types/data-structures}/base/iterable-entry-base.d.ts +0 -0
  261. package/dist/{data-structures → types/data-structures}/base/linear-base.d.ts +0 -0
  262. package/dist/{interfaces → types/interfaces}/doubly-linked-list.d.ts +0 -0
  263. package/dist/{interfaces → types/interfaces}/graph.d.ts +0 -0
  264. package/dist/{interfaces → types/interfaces}/heap.d.ts +0 -0
  265. package/dist/{interfaces → types/interfaces}/index.d.ts +0 -0
  266. package/dist/{interfaces → types/interfaces}/navigator.d.ts +0 -0
  267. package/dist/{interfaces → types/interfaces}/priority-queue.d.ts +0 -0
  268. package/dist/{interfaces → types/interfaces}/segment-tree.d.ts +0 -0
  269. package/dist/{interfaces → types/interfaces}/singly-linked-list.d.ts +0 -0
  270. package/dist/types/{common.d.ts → types/common.d.ts} +0 -0
  271. package/dist/types/{data-structures → types/data-structures}/base/base.d.ts +0 -0
  272. package/dist/{data-structures → types/types/data-structures}/index.d.ts +7 -7
  273. package/dist/{data-structures → types/types/data-structures}/linked-list/index.d.ts +0 -0
  274. package/dist/{data-structures → types/types/data-structures}/matrix/index.d.ts +1 -1
  275. /package/dist/{data-structures → types/types/data-structures}/priority-queue/index.d.ts +0 -0
  276. /package/dist/{data-structures → types/types/data-structures}/queue/index.d.ts +0 -0
  277. /package/dist/{data-structures → types/types/data-structures}/stack/index.d.ts +0 -0
  278. /package/dist/{data-structures → types/types/data-structures}/tree/index.d.ts +0 -0
  279. /package/dist/{data-structures → types/types/data-structures}/trie/index.d.ts +0 -0
  280. /package/dist/types/{utils → types/utils}/validate-type.d.ts +0 -0
  281. /package/dist/{utils → types/utils}/number.d.ts +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/index.ts","../../src/utils/utils.ts","../../src/data-structures/base/iterable-entry-base.ts","../../src/data-structures/base/iterable-element-base.ts","../../src/data-structures/heap/heap.ts","../../src/data-structures/base/linear-base.ts","../../src/data-structures/queue/queue.ts","../../src/data-structures/graph/abstract-graph.ts","../../src/data-structures/graph/directed-graph.ts","../../src/common/index.ts"],"sourcesContent":["/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\nexport * from './data-structures/graph/directed-graph';\nexport * from './data-structures/graph/abstract-graph';\nexport * from './types/data-structures/graph/directed-graph';\nexport * from './types/data-structures/graph/abstract-graph';\nexport * from './types/common';\nexport * from './types/utils';\nexport * from './common';","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\nimport type { Comparable, ComparablePrimitive, Trampoline, TrampolineThunk } from '../types';\n\n/**\n * The function generates a random UUID (Universally Unique Identifier) in TypeScript.\n * @returns A randomly generated UUID (Universally Unique Identifier) in the format\n * 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' where each 'x' is replaced with a random hexadecimal\n * character.\n */\nexport const uuidV4 = function () {\n return 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'.replace(/[x]/g, function (c) {\n const r = (Math.random() * 16) | 0,\n v = c == 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n};\n\n/**\n * The `arrayRemove` function removes elements from an array based on a specified predicate function\n * and returns the removed elements.\n * @param {T[]} array - An array of elements that you want to filter based on the provided predicate\n * function.\n * @param predicate - The `predicate` parameter is a function that takes three arguments:\n * @returns The `arrayRemove` function returns an array containing the elements that satisfy the given\n * `predicate` function.\n */\nexport const arrayRemove = function <T>(array: T[], predicate: (item: T, index: number, array: T[]) => boolean): T[] {\n let i = -1,\n len = array ? array.length : 0;\n const result = [];\n\n while (++i < len) {\n const value = array[i];\n if (predicate(value, i, array)) {\n result.push(value);\n Array.prototype.splice.call(array, i--, 1);\n len--;\n }\n }\n\n return result;\n};\n\n/**\n * The function `getMSB` returns the most significant bit of a given number.\n * @param {number} value - The `value` parameter is a number for which we want to find the position of\n * the Most Significant Bit (MSB). The function `getMSB` takes this number as input and calculates the\n * position of the MSB in its binary representation.\n * @returns The function `getMSB` returns the most significant bit (MSB) of the input `value`. If the\n * input value is less than or equal to 0, it returns 0. Otherwise, it calculates the position of the\n * MSB using the `Math.clz32` function and bitwise left shifts 1 to that position.\n */\nexport const getMSB = (value: number): number => {\n if (value <= 0) {\n return 0;\n }\n return 1 << (31 - Math.clz32(value));\n};\n\n/**\n * The `rangeCheck` function in TypeScript is used to validate if an index is within a specified range\n * and throws a `RangeError` with a custom message if it is out of bounds.\n * @param {number} index - The `index` parameter represents the value that you want to check if it\n * falls within a specified range.\n * @param {number} min - The `min` parameter represents the minimum value that the `index` should be\n * compared against in the `rangeCheck` function.\n * @param {number} max - The `max` parameter in the `rangeCheck` function represents the maximum value\n * that the `index` parameter is allowed to have. If the `index` is greater than this `max` value, a\n * `RangeError` will be thrown.\n * @param [message=Index out of bounds.] - The `message` parameter is a string that represents the\n * error message to be thrown if the index is out of bounds. By default, if no message is provided when\n * calling the `rangeCheck` function, the message \"Index out of bounds.\" will be used.\n */\nexport const rangeCheck = (index: number, min: number, max: number, message = 'Index out of bounds.'): void => {\n if (index < min || index > max) throw new RangeError(message);\n};\n\n/**\n * The function `throwRangeError` throws a RangeError with a custom message if called.\n * @param [message=The value is off-limits.] - The `message` parameter is a string that represents the\n * error message to be displayed when a `RangeError` is thrown. If no message is provided, the default\n * message is 'The value is off-limits.'.\n */\nexport const throwRangeError = (message = 'The value is off-limits.'): void => {\n throw new RangeError(message);\n};\n\n/**\n * The function `isWeakKey` checks if the input is an object or a function in TypeScript.\n * @param {unknown} input - The `input` parameter in the `isWeakKey` function is of type `unknown`,\n * which means it can be any type. The function checks if the `input` is an object (excluding `null`)\n * or a function, and returns a boolean indicating whether the `input` is a weak\n * @returns The function `isWeakKey` returns a boolean value indicating whether the input is an object\n * or a function.\n */\nexport const isWeakKey = (input: unknown): input is object => {\n const inputType = typeof input;\n return (inputType === 'object' && input !== null) || inputType === 'function';\n};\n\n/**\n * The function `calcMinUnitsRequired` calculates the minimum number of units required to accommodate a\n * given total quantity based on a specified unit size.\n * @param {number} totalQuantity - The `totalQuantity` parameter represents the total quantity of items\n * that need to be processed or handled.\n * @param {number} unitSize - The `unitSize` parameter represents the size of each unit or package. It\n * is used in the `calcMinUnitsRequired` function to calculate the minimum number of units required to\n * accommodate a total quantity of items.\n */\nexport const calcMinUnitsRequired = (totalQuantity: number, unitSize: number) =>\n Math.floor((totalQuantity + unitSize - 1) / unitSize);\n\n/**\n * The `roundFixed` function in TypeScript rounds a number to a specified number of decimal places.\n * @param {number} num - The `num` parameter is a number that you want to round to a certain number of\n * decimal places.\n * @param {number} [digit=10] - The `digit` parameter in the `roundFixed` function specifies the number\n * of decimal places to round the number to. By default, it is set to 10 if not provided explicitly.\n * @returns The function `roundFixed` returns a number that is rounded to the specified number of\n * decimal places (default is 10 decimal places).\n */\nexport const roundFixed = (num: number, digit: number = 10) => {\n const multiplier = Math.pow(10, digit);\n return Math.round(num * multiplier) / multiplier;\n};\n\n/**\n * The function `isPrimitiveComparable` checks if a value is a primitive type that can be compared.\n * @param {unknown} value - The `value` parameter in the `isPrimitiveComparable` function is of type\n * `unknown`, which means it can be any type. The function checks if the `value` is a primitive type\n * that can be compared, such as number, bigint, string, or boolean.\n * @returns The function `isPrimitiveComparable` returns a boolean value indicating whether the input\n * `value` is a primitive value that can be compared using standard comparison operators (<, >, <=,\n * >=).\n */\nfunction isPrimitiveComparable(value: unknown): value is ComparablePrimitive {\n const valueType = typeof value;\n if (valueType === 'number') return true;\n // if (valueType === 'number') return !Number.isNaN(value);\n return valueType === 'bigint' || valueType === 'string' || valueType === 'boolean';\n}\n\n/**\n * The function `tryObjectToPrimitive` attempts to convert an object to a comparable primitive value by\n * first checking the `valueOf` method and then the `toString` method.\n * @param {object} obj - The `obj` parameter in the `tryObjectToPrimitive` function is an object that\n * you want to convert to a primitive value. The function attempts to convert the object to a primitive\n * value by first checking if the object has a `valueOf` method. If the `valueOf` method exists, it\n * @returns The function `tryObjectToPrimitive` returns a value of type `ComparablePrimitive` if a\n * primitive comparable value is found within the object, or a string value if the object has a custom\n * `toString` method that does not return `'[object Object]'`. If neither condition is met, the\n * function returns `null`.\n */\nfunction tryObjectToPrimitive(obj: object): ComparablePrimitive | null {\n if (typeof obj.valueOf === 'function') {\n const valueOfResult = obj.valueOf();\n if (valueOfResult !== obj) {\n if (isPrimitiveComparable(valueOfResult)) return valueOfResult;\n if (typeof valueOfResult === 'object' && valueOfResult !== null) return tryObjectToPrimitive(valueOfResult);\n }\n }\n if (typeof obj.toString === 'function') {\n const stringResult = obj.toString();\n if (stringResult !== '[object Object]') return stringResult;\n }\n return null;\n}\n\n/**\n * The function `isComparable` in TypeScript checks if a value is comparable, handling primitive values\n * and objects with optional force comparison.\n * @param {unknown} value - The `value` parameter in the `isComparable` function represents the value\n * that you want to check if it is comparable. It can be of any type (`unknown`), and the function will\n * determine if it is comparable based on certain conditions.\n * @param [isForceObjectComparable=false] - The `isForceObjectComparable` parameter in the\n * `isComparable` function is a boolean flag that determines whether to treat non-primitive values as\n * comparable objects. When set to `true`, it forces the function to consider non-primitive values as\n * comparable objects, regardless of their type.\n * @returns The function `isComparable` returns a boolean value indicating whether the `value` is\n * considered comparable or not.\n */\nexport function isComparable(value: unknown, isForceObjectComparable = false): value is Comparable {\n if (value === null || value === undefined) return false;\n if (isPrimitiveComparable(value)) return true;\n\n if (typeof value !== 'object') return false;\n if (value instanceof Date) return true;\n // if (value instanceof Date) return !Number.isNaN(value.getTime());\n if (isForceObjectComparable) return true;\n const comparableValue = tryObjectToPrimitive(value);\n if (comparableValue === null || comparableValue === undefined) return false;\n return isPrimitiveComparable(comparableValue);\n}\n\n/**\n * Creates a trampoline thunk object.\n *\n * A \"thunk\" is a deferred computation — instead of performing a recursive call immediately,\n * it wraps the next step of the computation in a function. This allows recursive processes\n * to be executed iteratively, preventing stack overflows.\n *\n * @template T - The type of the final computation result.\n * @param computation - A function that, when executed, returns the next trampoline step.\n * @returns A TrampolineThunk object containing the deferred computation.\n */\nexport const makeTrampolineThunk = <T>(computation: () => Trampoline<T>): TrampolineThunk<T> => ({\n isThunk: true, // Marker indicating this is a thunk\n fn: computation // The deferred computation function\n});\n\n/**\n * Type guard to check whether a given value is a TrampolineThunk.\n *\n * This function is used to distinguish between a final computation result (value)\n * and a deferred computation (thunk).\n *\n * @template T - The type of the value being checked.\n * @param value - The value to test.\n * @returns True if the value is a valid TrampolineThunk, false otherwise.\n */\nexport const isTrampolineThunk = <T>(value: Trampoline<T>): value is TrampolineThunk<T> =>\n typeof value === 'object' && // Must be an object\n value !== null && // Must not be null\n 'isThunk' in value && // Must have the 'isThunk' property\n value.isThunk; // The flag must be true\n\n/**\n * Executes a trampoline computation until a final (non-thunk) result is obtained.\n *\n * The trampoline function repeatedly invokes the deferred computations (thunks)\n * in an iterative loop. This avoids deep recursive calls and prevents stack overflow,\n * which is particularly useful for implementing recursion in a stack-safe manner.\n *\n * @template T - The type of the final result.\n * @param initial - The initial Trampoline value or thunk to start execution from.\n * @returns The final result of the computation (a non-thunk value).\n */\nexport function trampoline<T>(initial: Trampoline<T>): T {\n let current = initial; // Start with the initial trampoline value\n while (isTrampolineThunk(current)) {\n // Keep unwrapping while we have thunks\n current = current.fn(); // Execute the deferred function to get the next step\n }\n return current; // Once no thunks remain, return the final result\n}\n\n/**\n * Wraps a recursive function inside a trampoline executor.\n *\n * This function transforms a potentially recursive function (that returns a Trampoline<Result>)\n * into a *stack-safe* function that executes iteratively using the `trampoline` runner.\n *\n * In other words, it allows you to write functions that look recursive,\n * but actually run in constant stack space.\n *\n * @template Args - The tuple type representing the argument list of the original function.\n * @template Result - The final return type after all trampoline steps are resolved.\n *\n * @param fn - A function that performs a single step of computation\n * and returns a Trampoline (either a final value or a deferred thunk).\n *\n * @returns A new function with the same arguments, but which automatically\n * runs the trampoline process and returns the *final result* instead\n * of a Trampoline.\n *\n * @example\n * // Example: Computing factorial in a stack-safe way\n * const factorial = makeTrampoline(function fact(n: number, acc: number = 1): Trampoline<number> {\n * return n === 0\n * ? acc\n * : makeTrampolineThunk(() => fact(n - 1, acc * n));\n * });\n *\n * console.log(factorial(100000)); // Works without stack overflow\n */\nexport function makeTrampoline<Args extends any[], Result>(\n fn: (...args: Args) => Trampoline<Result> // A function that returns a trampoline step\n): (...args: Args) => Result {\n // Return a wrapped function that automatically runs the trampoline execution loop\n return (...args: Args) => trampoline(fn(...args));\n}\n\n/**\n * Executes an asynchronous trampoline computation until a final (non-thunk) result is obtained.\n *\n * This function repeatedly invokes asynchronous deferred computations (thunks)\n * in an iterative loop. Each thunk may return either a Trampoline<T> or a Promise<Trampoline<T>>.\n *\n * It ensures that asynchronous recursive functions can run without growing the call stack,\n * making it suitable for stack-safe async recursion.\n *\n * @template T - The type of the final result.\n * @param initial - The initial Trampoline or Promise of Trampoline to start execution from.\n * @returns A Promise that resolves to the final result (a non-thunk value).\n */\nexport async function asyncTrampoline<T>(initial: Trampoline<T> | Promise<Trampoline<T>>): Promise<T> {\n let current = await initial; // Wait for the initial step to resolve if it's a Promise\n\n // Keep executing thunks until we reach a non-thunk (final) value\n while (isTrampolineThunk(current)) {\n current = await current.fn(); // Execute the thunk function (may be async)\n }\n\n // Once the final value is reached, return it\n return current;\n}\n\n/**\n * Wraps an asynchronous recursive function inside an async trampoline executor.\n *\n * This helper transforms a recursive async function that returns a Trampoline<Result>\n * (or Promise<Trampoline<Result>>) into a *stack-safe* async function that executes\n * iteratively via the `asyncTrampoline` runner.\n *\n * @template Args - The tuple type representing the argument list of the original function.\n * @template Result - The final return type after all async trampoline steps are resolved.\n *\n * @param fn - An async or sync function that performs a single step of computation\n * and returns a Trampoline (either a final value or a deferred thunk).\n *\n * @returns An async function with the same arguments, but which automatically\n * runs the trampoline process and resolves to the *final result*.\n *\n * @example\n * // Example: Async factorial using trampoline\n * const asyncFactorial = makeAsyncTrampoline(async function fact(\n * n: number,\n * acc: number = 1\n * ): Promise<Trampoline<number>> {\n * return n === 0\n * ? acc\n * : makeTrampolineThunk(() => fact(n - 1, acc * n));\n * });\n *\n * asyncFactorial(100000).then(console.log); // Works without stack overflow\n */\nexport function makeAsyncTrampoline<Args extends any[], Result>(\n fn: (...args: Args) => Trampoline<Result> | Promise<Trampoline<Result>>\n): (...args: Args) => Promise<Result> {\n // Return a wrapped async function that runs through the async trampoline loop\n return async (...args: Args): Promise<Result> => {\n return asyncTrampoline(fn(...args));\n };\n}\n","import type { EntryCallback, ReduceEntryCallback } from '../../types';\n\n/**\n * Iterable view over key-value entries.\n * @template K - Key type.\n * @template V - Value type.\n * @remarks Time O(1), Space O(1)\n */\nexport abstract class IterableEntryBase<K = any, V = any> {\n /**\n * Total number of entries.\n * @returns Entry count.\n * @remarks Time O(1), Space O(1)\n */\n abstract get size(): number;\n\n /**\n * Default iterator yielding `[key, value]` entries.\n * @returns Iterator of `[K, V]`.\n * @remarks Time O(n) to iterate, Space O(1)\n */\n *[Symbol.iterator](...args: any[]): IterableIterator<[K, V]> {\n yield* this._getIterator(...args);\n }\n\n /**\n * Iterate over `[key, value]` pairs (may yield `undefined` values).\n * @returns Iterator of `[K, V | undefined]`.\n * @remarks Time O(n), Space O(1)\n */\n *entries(): IterableIterator<[K, V | undefined]> {\n for (const item of this) {\n yield item;\n }\n }\n\n /**\n * Iterate over keys only.\n * @returns Iterator of keys.\n * @remarks Time O(n), Space O(1)\n */\n *keys(): IterableIterator<K> {\n for (const item of this) {\n yield item[0];\n }\n }\n\n /**\n * Iterate over values only.\n * @returns Iterator of values.\n * @remarks Time O(n), Space O(1)\n */\n *values(): IterableIterator<V> {\n for (const item of this) {\n yield item[1];\n }\n }\n\n /**\n * Test whether all entries satisfy the predicate.\n * @param predicate - `(key, value, index, self) => boolean`.\n * @param thisArg - Optional `this` for callback.\n * @returns `true` if all pass; otherwise `false`.\n * @remarks Time O(n), Space O(1)\n */\n every(predicate: EntryCallback<K, V, boolean>, thisArg?: any): boolean {\n let index = 0;\n for (const item of this) {\n if (!predicate.call(thisArg, item[0], item[1], index++, this)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Test whether any entry satisfies the predicate.\n * @param predicate - `(key, value, index, self) => boolean`.\n * @param thisArg - Optional `this` for callback.\n * @returns `true` if any passes; otherwise `false`.\n * @remarks Time O(n), Space O(1)\n */\n some(predicate: EntryCallback<K, V, boolean>, thisArg?: any): boolean {\n let index = 0;\n for (const item of this) {\n if (predicate.call(thisArg, item[0], item[1], index++, this)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Visit each entry, left-to-right.\n * @param callbackfn - `(key, value, index, self) => void`.\n * @param thisArg - Optional `this` for callback.\n * @remarks Time O(n), Space O(1)\n */\n forEach(callbackfn: EntryCallback<K, V, void>, thisArg?: any): void {\n let index = 0;\n for (const item of this) {\n const [key, value] = item;\n callbackfn.call(thisArg, key, value, index++, this);\n }\n }\n\n /**\n * Find the first entry that matches a predicate.\n * @param callbackfn - `(key, value, index, self) => boolean`.\n * @param thisArg - Optional `this` for callback.\n * @returns Matching `[key, value]` or `undefined`.\n * @remarks Time O(n), Space O(1)\n */\n find(callbackfn: EntryCallback<K, V, boolean>, thisArg?: any): [K, V] | undefined {\n let index = 0;\n for (const item of this) {\n const [key, value] = item;\n if (callbackfn.call(thisArg, key, value, index++, this)) return item;\n }\n return;\n }\n\n /**\n * Whether the given key exists.\n * @param key - Key to test.\n * @returns `true` if found; otherwise `false`.\n * @remarks Time O(n) generic, Space O(1)\n */\n has(key: K): boolean {\n for (const item of this) {\n const [itemKey] = item;\n if (itemKey === key) return true;\n }\n return false;\n }\n\n /**\n * Whether there exists an entry with the given value.\n * @param value - Value to test.\n * @returns `true` if found; otherwise `false`.\n * @remarks Time O(n), Space O(1)\n */\n hasValue(value: V): boolean {\n for (const [, elementValue] of this) {\n if (elementValue === value) return true;\n }\n return false;\n }\n\n /**\n * Get the value under a key.\n * @param key - Key to look up.\n * @returns Value or `undefined`.\n * @remarks Time O(n) generic, Space O(1)\n */\n get(key: K): V | undefined {\n for (const item of this) {\n const [itemKey, value] = item;\n if (itemKey === key) return value;\n }\n return;\n }\n\n /**\n * Reduce entries into a single accumulator.\n * @param callbackfn - `(acc, value, key, index, self) => acc`.\n * @param initialValue - Initial accumulator.\n * @returns Final accumulator.\n * @remarks Time O(n), Space O(1)\n */\n reduce<U>(callbackfn: ReduceEntryCallback<K, V, U>, initialValue: U): U {\n let accumulator = initialValue;\n let index = 0;\n for (const item of this) {\n const [key, value] = item;\n accumulator = callbackfn(accumulator, value, key, index++, this);\n }\n return accumulator;\n }\n\n /**\n * Visualize the iterable as an array of `[key, value]` pairs (or a custom string).\n * @returns Array of entries (default) or a string.\n * @remarks Time O(n), Space O(n)\n */\n toVisual(): [K, V][] | string {\n return [...this];\n }\n\n /**\n * Print a human-friendly representation to the console.\n * @remarks Time O(n), Space O(n)\n */\n print(): void {\n console.log(this.toVisual());\n }\n\n /**\n * Whether there are no entries.\n * @returns `true` if empty; `false` otherwise.\n * @remarks Time O(1) typical, Space O(1)\n */\n abstract isEmpty(): boolean;\n\n /**\n * Remove all entries.\n * @remarks Time O(n) typical, Space O(1)\n */\n abstract clear(): void;\n\n /**\n * Deep clone preserving the concrete subtype.\n * @returns A new instance of the same concrete class (`this` type).\n * @remarks Time O(n) typical, Space O(n)\n */\n abstract clone(): this;\n\n /**\n * Map entries using an implementation-specific strategy.\n * @remarks Time O(n), Space O(n)\n */\n abstract map(...args: any[]): any;\n\n /**\n * Filter entries and return the same-species structure.\n * @returns A new instance of the same concrete class (`this` type).\n * @remarks Time O(n), Space O(n)\n */\n abstract filter(...args: any[]): this;\n\n /**\n * Underlying iterator for the default iteration protocol.\n * @returns Iterator of `[K, V]`.\n * @remarks Time O(n), Space O(1)\n */\n protected abstract _getIterator(...args: any[]): IterableIterator<[K, V]>;\n}\n","import type { ElementCallback, IterableElementBaseOptions, ReduceElementCallback } from '../../types';\n\n/**\n * Base class that makes a data structure iterable and provides common\n * element-wise utilities (e.g., map/filter/reduce/find).\n *\n * @template E The public element type yielded by the structure.\n * @template R The underlying \"raw\" element type used internally or by converters.\n *\n * @remarks\n * This class implements the JavaScript iteration protocol (via `Symbol.iterator`)\n * and offers array-like helpers with predictable time/space complexity.\n */\nexport abstract class IterableElementBase<E, R> implements Iterable<E> {\n /**\n * Create a new iterable base.\n *\n * @param options Optional behavior overrides. When provided, a `toElementFn`\n * is used to convert a raw element (`R`) into a public element (`E`).\n *\n * @remarks\n * Time O(1), Space O(1).\n */\n protected constructor(options?: IterableElementBaseOptions<E, R>) {\n if (options) {\n const { toElementFn } = options;\n if (typeof toElementFn === 'function') this._toElementFn = toElementFn;\n else if (toElementFn) throw new TypeError('toElementFn must be a function type');\n }\n }\n\n /**\n * The converter used to transform a raw element (`R`) into a public element (`E`).\n *\n * @remarks\n * Time O(1), Space O(1).\n */\n protected _toElementFn?: (rawElement: R) => E;\n\n /**\n * Exposes the current `toElementFn`, if configured.\n *\n * @returns The converter function or `undefined` when not set.\n * @remarks\n * Time O(1), Space O(1).\n */\n get toElementFn(): ((rawElement: R) => E) | undefined {\n return this._toElementFn;\n }\n\n /**\n * Returns an iterator over the structure's elements.\n *\n * @param args Optional iterator arguments forwarded to the internal iterator.\n * @returns An `IterableIterator<E>` that yields the elements in traversal order.\n *\n * @remarks\n * Producing the iterator is O(1); consuming the entire iterator is Time O(n) with O(1) extra space.\n */\n *[Symbol.iterator](...args: unknown[]): IterableIterator<E> {\n yield* this._getIterator(...args);\n }\n\n /**\n * Returns an iterator over the values (alias of the default iterator).\n *\n * @returns An `IterableIterator<E>` over all elements.\n * @remarks\n * Creating the iterator is O(1); full iteration is Time O(n), Space O(1).\n */\n *values(): IterableIterator<E> {\n for (const item of this) yield item;\n }\n\n /**\n * Tests whether all elements satisfy the predicate.\n *\n * @template TReturn\n * @param predicate Function invoked for each element with signature `(value, index, self)`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns `true` if every element passes; otherwise `false`.\n *\n * @remarks\n * Time O(n) in the worst case; may exit early when the first failure is found. Space O(1).\n */\n every(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): boolean {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n if (!predicate(item, index++, this)) return false;\n } else {\n const fn = predicate as (this: unknown, v: E, i: number, self: this) => boolean;\n if (!fn.call(thisArg, item, index++, this)) return false;\n }\n }\n return true;\n }\n\n /**\n * Tests whether at least one element satisfies the predicate.\n *\n * @param predicate Function invoked for each element with signature `(value, index, self)`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns `true` if any element passes; otherwise `false`.\n *\n * @remarks\n * Time O(n) in the worst case; may exit early on first success. Space O(1).\n */\n some(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): boolean {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n if (predicate(item, index++, this)) return true;\n } else {\n const fn = predicate as (this: unknown, v: E, i: number, self: this) => boolean;\n if (fn.call(thisArg, item, index++, this)) return true;\n }\n }\n return false;\n }\n\n /**\n * Invokes a callback for each element in iteration order.\n *\n * @param callbackfn Function invoked per element with signature `(value, index, self)`.\n * @param thisArg Optional `this` binding for the callback.\n * @returns `void`.\n *\n * @remarks\n * Time O(n), Space O(1).\n */\n forEach(callbackfn: ElementCallback<E, R, void>, thisArg?: unknown): void {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n callbackfn(item, index++, this);\n } else {\n const fn = callbackfn as (this: unknown, v: E, i: number, self: this) => void;\n fn.call(thisArg, item, index++, this);\n }\n }\n }\n\n /**\n * Finds the first element that satisfies the predicate and returns it.\n *\n * @overload\n * Finds the first element of type `S` (a subtype of `E`) that satisfies the predicate and returns it.\n * @template S\n * @param predicate Type-guard predicate: `(value, index, self) => value is S`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns The matched element typed as `S`, or `undefined` if not found.\n *\n * @overload\n * @param predicate Boolean predicate: `(value, index, self) => boolean`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns The first matching element as `E`, or `undefined` if not found.\n *\n * @remarks\n * Time O(n) in the worst case; may exit early on the first match. Space O(1).\n */\n find<S extends E>(predicate: ElementCallback<E, R, S>, thisArg?: unknown): S | undefined;\n find(predicate: ElementCallback<E, R, unknown>, thisArg?: unknown): E | undefined;\n\n // Implementation signature\n find(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): E | undefined {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n if (predicate(item, index++, this)) return item;\n } else {\n const fn = predicate as (this: unknown, v: E, i: number, self: this) => boolean;\n if (fn.call(thisArg, item, index++, this)) return item;\n }\n }\n return;\n }\n\n /**\n * Checks whether a strictly-equal element exists in the structure.\n *\n * @param element The element to test with `===` equality.\n * @returns `true` if an equal element is found; otherwise `false`.\n *\n * @remarks\n * Time O(n) in the worst case. Space O(1).\n */\n has(element: E): boolean {\n for (const ele of this) if (ele === element) return true;\n return false;\n }\n\n reduce(callbackfn: ReduceElementCallback<E, R>): E;\n reduce(callbackfn: ReduceElementCallback<E, R>, initialValue: E): E;\n reduce<U>(callbackfn: ReduceElementCallback<E, R, U>, initialValue: U): U;\n\n /**\n * Reduces all elements to a single accumulated value.\n *\n * @overload\n * @param callbackfn Reducer of signature `(acc, value, index, self) => nextAcc`. The first element is used as the initial accumulator.\n * @returns The final accumulated value typed as `E`.\n *\n * @overload\n * @param callbackfn Reducer of signature `(acc, value, index, self) => nextAcc`.\n * @param initialValue The initial accumulator value of type `E`.\n * @returns The final accumulated value typed as `E`.\n *\n * @overload\n * @template U The accumulator type when it differs from `E`.\n * @param callbackfn Reducer of signature `(acc: U, value, index, self) => U`.\n * @param initialValue The initial accumulator value of type `U`.\n * @returns The final accumulated value typed as `U`.\n *\n * @remarks\n * Time O(n), Space O(1). Throws if called on an empty structure without `initialValue`.\n */\n reduce<U>(callbackfn: ReduceElementCallback<E, R, U>, initialValue?: U): U {\n let index = 0;\n const iter = this[Symbol.iterator]();\n let acc: U;\n\n if (arguments.length >= 2) {\n acc = initialValue as U;\n } else {\n const first = iter.next();\n if (first.done) throw new TypeError('Reduce of empty structure with no initial value');\n acc = first.value as unknown as U;\n index = 1;\n }\n\n for (const value of iter as unknown as Iterable<E>) {\n acc = callbackfn(acc, value, index++, this);\n }\n return acc;\n }\n\n /**\n * Materializes the elements into a new array.\n *\n * @returns A shallow array copy of the iteration order.\n * @remarks\n * Time O(n), Space O(n).\n */\n toArray(): E[] {\n return [...this];\n }\n\n /**\n * Returns a representation of the structure suitable for quick visualization.\n * Defaults to an array of elements; subclasses may override to provide richer visuals.\n *\n * @returns A visual representation (array by default).\n * @remarks\n * Time O(n), Space O(n).\n */\n toVisual(): E[] {\n return [...this];\n }\n\n /**\n * Prints `toVisual()` to the console. Intended for quick debugging.\n *\n * @returns `void`.\n * @remarks\n * Time O(n) due to materialization, Space O(n) for the intermediate representation.\n */\n print(): void {\n console.log(this.toVisual());\n }\n\n /**\n * Indicates whether the structure currently contains no elements.\n *\n * @returns `true` if empty; otherwise `false`.\n * @remarks\n * Expected Time O(1), Space O(1) for most implementations.\n */\n abstract isEmpty(): boolean;\n\n /**\n * Removes all elements from the structure.\n *\n * @returns `void`.\n * @remarks\n * Expected Time O(1) or O(n) depending on the implementation; Space O(1).\n */\n abstract clear(): void;\n\n /**\n * Creates a structural copy with the same element values and configuration.\n *\n * @returns A clone of the current instance (same concrete type).\n * @remarks\n * Expected Time O(n) to copy elements; Space O(n).\n */\n abstract clone(): this;\n\n /**\n * Maps each element to a new element and returns a new iterable structure.\n *\n * @template EM The mapped element type.\n * @template RM The mapped raw element type used internally by the target structure.\n * @param callback Function with signature `(value, index, self) => mapped`.\n * @param options Optional options for the returned structure, including its `toElementFn`.\n * @param thisArg Optional `this` binding for the callback.\n * @returns A new `IterableElementBase<EM, RM>` containing mapped elements.\n *\n * @remarks\n * Time O(n), Space O(n).\n */\n abstract map<EM, RM>(\n callback: ElementCallback<E, R, EM>,\n options?: IterableElementBaseOptions<EM, RM>,\n thisArg?: unknown\n ): IterableElementBase<EM, RM>;\n\n /**\n * Maps each element to the same element type and returns the same concrete structure type.\n *\n * @param callback Function with signature `(value, index, self) => mappedValue`.\n * @param thisArg Optional `this` binding for the callback.\n * @returns A new instance of the same concrete type with mapped elements.\n *\n * @remarks\n * Time O(n), Space O(n).\n */\n abstract mapSame(callback: ElementCallback<E, R, E>, thisArg?: unknown): this;\n\n /**\n * Filters elements using the provided predicate and returns the same concrete structure type.\n *\n * @param predicate Function with signature `(value, index, self) => boolean`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns A new instance of the same concrete type containing only elements that pass the predicate.\n *\n * @remarks\n * Time O(n), Space O(k) where `k` is the number of kept elements.\n */\n abstract filter(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): this;\n\n /**\n * Internal iterator factory used by the default iterator.\n *\n * @param args Optional iterator arguments.\n * @returns An iterator over elements.\n *\n * @remarks\n * Implementations should yield in O(1) per element with O(1) extra space when possible.\n */\n protected abstract _getIterator(...args: unknown[]): IterableIterator<E>;\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type { Comparator, DFSOrderPattern, ElementCallback, HeapOptions } from '../../types';\nimport { IterableElementBase } from '../base';\n\n/**\n * Binary heap with pluggable comparator; supports fast insertion and removal of the top element.\n * @remarks Time O(1), Space O(1)\n * @template E\n * @template R\n * 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.\n * 2. Heap Properties: Each node in a heap follows a specific order property, which varies depending on the type of heap:\n * Max Heap: The value of each parent node is greater than or equal to the value of its children.\n * Min Heap: The value of each parent node is less than or equal to the value of its children.\n * 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.\n * 4. Efficient Insertion and Deletion: Due to its structure, a heap allows for insertion and deletion operations in logarithmic time (O(log n)).\n * 5. Managing Dynamic Data Sets: Heaps effectively manage dynamic data sets, especially when frequent access to the largest or smallest elements is required.\n * 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.\n * 7. Efficient Sorting Algorithms: For example, heap sort. Heap sort uses the properties of a heap to sort elements.\n * 8. Graph Algorithms: Such as Dijkstra's shortest path algorithm and Prime's minimum-spanning tree algorithm, which use heaps to improve performance.\n * @example\n * // Use Heap to sort an array\n * function heapSort(arr: number[]): number[] {\n * const heap = new Heap<number>(arr, { comparator: (a, b) => a - b });\n * const sorted: number[] = [];\n * while (!heap.isEmpty()) {\n * sorted.push(heap.poll()!); // Poll minimum element\n * }\n * return sorted;\n * }\n *\n * const array = [5, 3, 8, 4, 1, 2];\n * console.log(heapSort(array)); // [1, 2, 3, 4, 5, 8]\n * @example\n * // Use Heap to solve top k problems\n * function topKElements(arr: number[], k: number): number[] {\n * const heap = new Heap<number>([], { comparator: (a, b) => b - a }); // Max heap\n * arr.forEach(num => {\n * heap.add(num);\n * if (heap.size > k) heap.poll(); // Keep the heap size at K\n * });\n * return heap.toArray();\n * }\n *\n * const numbers = [10, 30, 20, 5, 15, 25];\n * console.log(topKElements(numbers, 3)); // [15, 10, 5]\n * @example\n * // Use Heap to merge sorted sequences\n * function mergeSortedSequences(sequences: number[][]): number[] {\n * const heap = new Heap<{ value: number; seqIndex: number; itemIndex: number }>([], {\n * comparator: (a, b) => a.value - b.value // Min heap\n * });\n *\n * // Initialize heap\n * sequences.forEach((seq, seqIndex) => {\n * if (seq.length) {\n * heap.add({ value: seq[0], seqIndex, itemIndex: 0 });\n * }\n * });\n *\n * const merged: number[] = [];\n * while (!heap.isEmpty()) {\n * const { value, seqIndex, itemIndex } = heap.poll()!;\n * merged.push(value);\n *\n * if (itemIndex + 1 < sequences[seqIndex].length) {\n * heap.add({\n * value: sequences[seqIndex][itemIndex + 1],\n * seqIndex,\n * itemIndex: itemIndex + 1\n * });\n * }\n * }\n *\n * return merged;\n * }\n *\n * const sequences = [\n * [1, 4, 7],\n * [2, 5, 8],\n * [3, 6, 9]\n * ];\n * console.log(mergeSortedSequences(sequences)); // [1, 2, 3, 4, 5, 6, 7, 8, 9]\n * @example\n * // Use Heap to dynamically maintain the median\n * class MedianFinder {\n * private low: MaxHeap<number>; // Max heap, stores the smaller half\n * private high: MinHeap<number>; // Min heap, stores the larger half\n *\n * constructor() {\n * this.low = new MaxHeap<number>([]);\n * this.high = new MinHeap<number>([]);\n * }\n *\n * addNum(num: number): void {\n * if (this.low.isEmpty() || num <= this.low.peek()!) this.low.add(num);\n * else this.high.add(num);\n *\n * // Balance heaps\n * if (this.low.size > this.high.size + 1) this.high.add(this.low.poll()!);\n * else if (this.high.size > this.low.size) this.low.add(this.high.poll()!);\n * }\n *\n * findMedian(): number {\n * if (this.low.size === this.high.size) return (this.low.peek()! + this.high.peek()!) / 2;\n * return this.low.peek()!;\n * }\n * }\n *\n * const medianFinder = new MedianFinder();\n * medianFinder.addNum(10);\n * console.log(medianFinder.findMedian()); // 10\n * medianFinder.addNum(20);\n * console.log(medianFinder.findMedian()); // 15\n * medianFinder.addNum(30);\n * console.log(medianFinder.findMedian()); // 20\n * medianFinder.addNum(40);\n * console.log(medianFinder.findMedian()); // 25\n * medianFinder.addNum(50);\n * console.log(medianFinder.findMedian()); // 30\n * @example\n * // Use Heap for load balancing\n * function loadBalance(requests: number[], servers: number): number[] {\n * const serverHeap = new Heap<{ id: number; load: number }>([], { comparator: (a, b) => a.load - b.load }); // min heap\n * const serverLoads = new Array(servers).fill(0);\n *\n * for (let i = 0; i < servers; i++) {\n * serverHeap.add({ id: i, load: 0 });\n * }\n *\n * requests.forEach(req => {\n * const server = serverHeap.poll()!;\n * serverLoads[server.id] += req;\n * server.load += req;\n * serverHeap.add(server); // The server after updating the load is re-entered into the heap\n * });\n *\n * return serverLoads;\n * }\n *\n * const requests = [5, 2, 8, 3, 7];\n * console.log(loadBalance(requests, 3)); // [12, 8, 5]\n * @example\n * // Use Heap to schedule tasks\n * type Task = [string, number];\n *\n * function scheduleTasks(tasks: Task[], machines: number): Map<number, Task[]> {\n * const machineHeap = new Heap<{ id: number; load: number }>([], { comparator: (a, b) => a.load - b.load }); // Min heap\n * const allocation = new Map<number, Task[]>();\n *\n * // Initialize the load on each machine\n * for (let i = 0; i < machines; i++) {\n * machineHeap.add({ id: i, load: 0 });\n * allocation.set(i, []);\n * }\n *\n * // Assign tasks\n * tasks.forEach(([task, load]) => {\n * const machine = machineHeap.poll()!;\n * allocation.get(machine.id)!.push([task, load]);\n * machine.load += load;\n * machineHeap.add(machine); // The machine after updating the load is re-entered into the heap\n * });\n *\n * return allocation;\n * }\n *\n * const tasks: Task[] = [\n * ['Task1', 3],\n * ['Task2', 1],\n * ['Task3', 2],\n * ['Task4', 5],\n * ['Task5', 4]\n * ];\n * const expectedMap = new Map<number, Task[]>();\n * expectedMap.set(0, [\n * ['Task1', 3],\n * ['Task4', 5]\n * ]);\n * expectedMap.set(1, [\n * ['Task2', 1],\n * ['Task3', 2],\n * ['Task5', 4]\n * ]);\n * console.log(scheduleTasks(tasks, 2)); // expectedMap\n */\nexport class Heap<E = any, R = any> extends IterableElementBase<E, R> {\n protected _equals: (a: E, b: E) => boolean = Object.is;\n\n /**\n * Create a Heap and optionally bulk-insert elements.\n * @remarks Time O(N), Space O(N)\n * @param [elements] - Iterable of elements (or raw values if toElementFn is set).\n * @param [options] - Options such as comparator and toElementFn.\n * @returns New Heap instance.\n */\n\n constructor(elements: Iterable<E | R> = [], options?: HeapOptions<E, R>) {\n super(options);\n\n if (options) {\n const { comparator } = options;\n if (comparator) this._comparator = comparator;\n }\n\n this.addMany(elements as Iterable<E | R>);\n }\n\n protected _elements: E[] = [];\n\n /**\n * Get the backing array of the heap.\n * @remarks Time O(1), Space O(1)\n * @returns Internal elements array.\n */\n\n get elements(): E[] {\n return this._elements;\n }\n\n /**\n * Get the number of elements.\n * @remarks Time O(1), Space O(1)\n * @returns Heap size.\n */\n\n get size(): number {\n return this.elements.length;\n }\n\n /**\n * Get the last leaf element.\n * @remarks Time O(1), Space O(1)\n * @returns Last element or undefined.\n */\n\n get leaf(): E | undefined {\n return this.elements[this.size - 1] ?? undefined;\n }\n\n /**\n * Create a heap of the same class from an iterable.\n * @remarks Time O(N), Space O(N)\n * @template T\n * @template R\n * @template S\n * @param [elements] - Iterable of elements or raw records.\n * @param [options] - Heap options including comparator.\n * @returns A new heap instance of this class.\n */\n\n static from<T, R = any, S extends Heap<T, R> = Heap<T, R>>(\n this: new (elements?: Iterable<T | R>, options?: HeapOptions<T, R>) => S,\n elements?: Iterable<T | R>,\n options?: HeapOptions<T, R>\n ): S {\n return new this(elements, options);\n }\n\n /**\n * Build a Heap from an iterable in linear time given a comparator.\n * @remarks Time O(N), Space O(N)\n * @template EE\n * @template RR\n * @param elements - Iterable of elements.\n * @param options - Heap options including comparator.\n * @returns A new Heap built from elements.\n */\n\n static heapify<EE = any, RR = any>(elements: Iterable<EE>, options: HeapOptions<EE, RR>): Heap<EE, RR> {\n return new Heap<EE, RR>(elements, options);\n }\n\n /**\n * Insert an element.\n * @remarks Time O(1) amortized, Space O(1)\n * @param element - Element to insert.\n * @returns True.\n */\n\n add(element: E): boolean {\n this._elements.push(element);\n return this._bubbleUp(this.elements.length - 1);\n }\n\n /**\n * Insert many elements from an iterable.\n * @remarks Time O(N log N), Space O(1)\n * @param elements - Iterable of elements or raw values.\n * @returns Array of per-element success flags.\n */\n\n addMany(elements: Iterable<E | R>): boolean[] {\n const flags: boolean[] = [];\n for (const el of elements) {\n if (this.toElementFn) {\n const ok = this.add(this.toElementFn(el as R));\n flags.push(ok);\n } else {\n const ok = this.add(el as E);\n flags.push(ok);\n }\n }\n return flags;\n }\n\n /**\n * Remove and return the top element.\n * @remarks Time O(log N), Space O(1)\n * @returns Top element or undefined.\n */\n\n poll(): E | undefined {\n if (this.elements.length === 0) return;\n const value = this.elements[0];\n const last = this.elements.pop()!;\n if (this.elements.length) {\n this.elements[0] = last;\n this._sinkDown(0, this.elements.length >> 1);\n }\n return value;\n }\n\n /**\n * Get the current top element without removing it.\n * @remarks Time O(1), Space O(1)\n * @returns Top element or undefined.\n */\n\n peek(): E | undefined {\n return this.elements[0];\n }\n\n /**\n * Check whether the heap is empty.\n * @remarks Time O(1), Space O(1)\n * @returns True if size is 0.\n */\n\n isEmpty(): boolean {\n return this.size === 0;\n }\n\n /**\n * Remove all elements.\n * @remarks Time O(1), Space O(1)\n * @returns void\n */\n\n clear(): void {\n this._elements = [];\n }\n\n /**\n * Replace the backing array and rebuild the heap.\n * @remarks Time O(N), Space O(N)\n * @param elements - Iterable used to refill the heap.\n * @returns Array of per-node results from fixing steps.\n */\n\n refill(elements: Iterable<E>): boolean[] {\n this._elements = Array.from(elements);\n return this.fix();\n }\n\n /**\n * Check if an equal element exists in the heap.\n * @remarks Time O(N), Space O(1)\n * @param element - Element to search for.\n * @returns True if found.\n */\n\n override has(element: E): boolean {\n for (const el of this.elements) if (this._equals(el, element)) return true;\n return false;\n }\n\n /**\n * Delete one occurrence of an element.\n * @remarks Time O(N), Space O(1)\n * @param element - Element to delete.\n * @returns True if an element was removed.\n */\n\n delete(element: E): boolean {\n let index = -1;\n for (let i = 0; i < this.elements.length; i++) {\n if (this._equals(this.elements[i], element)) {\n index = i;\n break;\n }\n }\n if (index < 0) return false;\n if (index === 0) {\n this.poll();\n } else if (index === this.elements.length - 1) {\n this.elements.pop();\n } else {\n this.elements.splice(index, 1, this.elements.pop()!);\n this._bubbleUp(index);\n this._sinkDown(index, this.elements.length >> 1);\n }\n return true;\n }\n\n /**\n * Delete the first element that matches a predicate.\n * @remarks Time O(N), Space O(1)\n * @param predicate - Function (element, index, heap) → boolean.\n * @returns True if an element was removed.\n */\n\n deleteBy(predicate: (element: E, index: number, heap: this) => boolean): boolean {\n let idx = -1;\n for (let i = 0; i < this.elements.length; i++) {\n if (predicate(this.elements[i], i, this)) {\n idx = i;\n break;\n }\n }\n if (idx < 0) return false;\n if (idx === 0) {\n this.poll();\n } else if (idx === this.elements.length - 1) {\n this.elements.pop();\n } else {\n this.elements.splice(idx, 1, this.elements.pop()!);\n this._bubbleUp(idx);\n this._sinkDown(idx, this.elements.length >> 1);\n }\n return true;\n }\n\n /**\n * Set the equality comparator used by has/delete operations.\n * @remarks Time O(1), Space O(1)\n * @param equals - Equality predicate (a, b) → boolean.\n * @returns This heap.\n */\n\n setEquality(equals: (a: E, b: E) => boolean): this {\n this._equals = equals;\n return this;\n }\n\n /**\n * Traverse the binary heap as a complete binary tree and collect elements.\n * @remarks Time O(N), Space O(H)\n * @param [order] - Traversal order: 'PRE' | 'IN' | 'POST'.\n * @returns Array of visited elements.\n */\n\n dfs(order: DFSOrderPattern = 'PRE'): E[] {\n const result: E[] = [];\n const _dfs = (index: number) => {\n const left = 2 * index + 1,\n right = left + 1;\n if (index < this.size) {\n if (order === 'IN') {\n _dfs(left);\n result.push(this.elements[index]);\n _dfs(right);\n } else if (order === 'PRE') {\n result.push(this.elements[index]);\n _dfs(left);\n _dfs(right);\n } else if (order === 'POST') {\n _dfs(left);\n _dfs(right);\n result.push(this.elements[index]);\n }\n }\n };\n _dfs(0);\n return result;\n }\n\n /**\n * Restore heap order bottom-up (heapify in-place).\n * @remarks Time O(N), Space O(1)\n * @returns Array of per-node results from fixing steps.\n */\n\n fix(): boolean[] {\n const results: boolean[] = [];\n for (let i = Math.floor(this.size / 2) - 1; i >= 0; i--) {\n results.push(this._sinkDown(i, this.elements.length >> 1));\n }\n return results;\n }\n\n /**\n * Return all elements in ascending order by repeatedly polling.\n * @remarks Time O(N log N), Space O(N)\n * @returns Sorted array of elements.\n */\n\n sort(): E[] {\n const visited: E[] = [];\n const cloned = this._createInstance();\n for (const x of this.elements) cloned.add(x);\n while (!cloned.isEmpty()) {\n const top = cloned.poll();\n if (top !== undefined) visited.push(top);\n }\n return visited;\n }\n\n /**\n * Deep clone this heap.\n * @remarks Time O(N), Space O(N)\n * @returns A new heap with the same elements.\n */\n\n clone(): this {\n const next = this._createInstance();\n for (const x of this.elements) next.add(x);\n return next;\n }\n\n /**\n * Filter elements into a new heap of the same class.\n * @remarks Time O(N log N), Space O(N)\n * @param callback - Predicate (element, index, heap) → boolean to keep element.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new heap with the kept elements.\n */\n\n filter(callback: ElementCallback<E, R, boolean>, thisArg?: unknown): this {\n const out = this._createInstance();\n let i = 0;\n for (const x of this) {\n if (thisArg === undefined ? callback(x, i++, this) : callback.call(thisArg, x, i++, this)) {\n out.add(x);\n } else {\n i++;\n }\n }\n return out;\n }\n\n /**\n * Map elements into a new heap of possibly different element type.\n * @remarks Time O(N log N), Space O(N)\n * @template EM\n * @template RM\n * @param callback - Mapping function (element, index, heap) → newElement.\n * @param options - Options for the output heap, including comparator for EM.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new heap with mapped elements.\n */\n\n map<EM, RM>(\n callback: ElementCallback<E, R, EM>,\n options: HeapOptions<EM, RM> & { comparator: Comparator<EM> },\n thisArg?: unknown\n ): Heap<EM, RM> {\n const { comparator, toElementFn, ...rest } = options ?? {};\n if (!comparator) throw new TypeError('Heap.map requires options.comparator for EM');\n const out = this._createLike<EM, RM>([], { ...rest, comparator, toElementFn });\n let i = 0;\n for (const x of this) {\n const v = thisArg === undefined ? callback(x, i++, this) : callback.call(thisArg, x, i++, this);\n out.add(v);\n }\n return out;\n }\n\n /**\n * Map elements into a new heap of the same element type.\n * @remarks Time O(N log N), Space O(N)\n * @param callback - Mapping function (element, index, heap) → element.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new heap with mapped elements.\n */\n\n mapSame(callback: ElementCallback<E, R, E>, thisArg?: unknown): this {\n const out = this._createInstance();\n let i = 0;\n for (const x of this) {\n const v = thisArg === undefined ? callback(x, i++, this) : callback.call(thisArg, x, i++, this);\n out.add(v);\n }\n return out;\n }\n\n protected _DEFAULT_COMPARATOR = (a: E, b: E): number => {\n if (typeof a === 'object' || typeof b === 'object') {\n throw TypeError('When comparing object types, define a custom comparator in options.');\n }\n if ((a as unknown as number) > (b as unknown as number)) return 1;\n if ((a as unknown as number) < (b as unknown as number)) return -1;\n return 0;\n };\n\n protected _comparator: Comparator<E> = this._DEFAULT_COMPARATOR; /**\n * Get the comparator used to order elements.\n * @remarks Time O(1), Space O(1)\n * @returns Comparator function.\n */\n /**\n * Get the comparator used to order elements.\n * @remarks Time O(1), Space O(1)\n * @returns Comparator function.\n */\n\n get comparator() {\n return this._comparator;\n }\n\n protected *_getIterator(): IterableIterator<E> {\n for (const element of this.elements) yield element;\n }\n\n protected _bubbleUp(index: number): boolean {\n const element = this.elements[index];\n while (index > 0) {\n const parent = (index - 1) >> 1;\n const parentItem = this.elements[parent];\n if (this.comparator(parentItem, element) <= 0) break;\n this.elements[index] = parentItem;\n index = parent;\n }\n this.elements[index] = element;\n return true;\n }\n\n protected _sinkDown(index: number, halfLength: number): boolean {\n const element = this.elements[index];\n while (index < halfLength) {\n let left = (index << 1) | 1;\n const right = left + 1;\n let minItem = this.elements[left];\n if (right < this.elements.length && this.comparator(minItem, this.elements[right]) > 0) {\n left = right;\n minItem = this.elements[right];\n }\n if (this.comparator(minItem, element) >= 0) break;\n this.elements[index] = minItem;\n index = left;\n }\n this.elements[index] = element;\n return true;\n }\n\n /**\n * (Protected) Create an empty instance of the same concrete class.\n * @remarks Time O(1), Space O(1)\n * @param [options] - Options to override comparator or toElementFn.\n * @returns A like-kind empty heap instance.\n */\n\n protected _createInstance(options?: HeapOptions<E, R>): this {\n const Ctor: any = this.constructor;\n const next: any = new Ctor([], { comparator: this.comparator, toElementFn: this.toElementFn, ...(options ?? {}) });\n return next as this;\n }\n\n /**\n * (Protected) Create a like-kind instance seeded by elements.\n * @remarks Time O(N log N), Space O(N)\n * @template EM\n * @template RM\n * @param [elements] - Iterable of elements or raw values to seed.\n * @param [options] - Options forwarded to the constructor.\n * @returns A like-kind heap instance.\n */\n\n protected _createLike<EM, RM>(\n elements: Iterable<EM> | Iterable<RM> = [],\n options?: HeapOptions<EM, RM>\n ): Heap<EM, RM> {\n const Ctor: any = this.constructor;\n return new Ctor(elements, options) as Heap<EM, RM>;\n }\n\n /**\n * (Protected) Spawn an empty like-kind heap instance.\n * @remarks Time O(1), Space O(1)\n * @template EM\n * @template RM\n * @param [options] - Options forwarded to the constructor.\n * @returns An empty like-kind heap instance.\n */\n\n protected _spawnLike<EM, RM>(options?: HeapOptions<EM, RM>): Heap<EM, RM> {\n return this._createLike<EM, RM>([], options);\n }\n}\n\n/**\n * Node container used by FibonacciHeap.\n * @remarks Time O(1), Space O(1)\n * @template E\n */\nexport class FibonacciHeapNode<E> {\n element: E;\n degree: number;\n left?: FibonacciHeapNode<E>;\n right?: FibonacciHeapNode<E>;\n child?: FibonacciHeapNode<E>;\n parent?: FibonacciHeapNode<E>;\n marked: boolean;\n\n constructor(element: E, degree = 0) {\n this.element = element;\n this.degree = degree;\n this.marked = false;\n }\n}\n\n/**\n * Fibonacci heap (min-heap) optimized for fast merges and amortized operations.\n * @remarks Time O(1), Space O(1)\n * @template E\n * @example examples will be generated by unit test\n */\nexport class FibonacciHeap<E> {\n /**\n * Create a FibonacciHeap.\n * @remarks Time O(1), Space O(1)\n * @param [comparator] - Comparator to order elements (min-heap by default).\n * @returns New FibonacciHeap instance.\n */\n\n constructor(comparator?: Comparator<E>) {\n this.clear();\n this._comparator = comparator || this._defaultComparator;\n if (typeof this.comparator !== 'function') throw new Error('FibonacciHeap: comparator must be a function.');\n }\n\n protected _root?: FibonacciHeapNode<E>;\n\n /**\n * Get the circular root list head.\n * @remarks Time O(1), Space O(1)\n * @returns Root node or undefined.\n */\n\n get root(): FibonacciHeapNode<E> | undefined {\n return this._root;\n }\n\n protected _size = 0;\n get size(): number {\n return this._size;\n }\n\n protected _min?: FibonacciHeapNode<E>;\n\n /**\n * Get the current minimum node.\n * @remarks Time O(1), Space O(1)\n * @returns Min node or undefined.\n */\n\n get min(): FibonacciHeapNode<E> | undefined {\n return this._min;\n }\n\n protected _comparator: Comparator<E>;\n get comparator(): Comparator<E> {\n return this._comparator;\n }\n\n clear(): void {\n this._root = undefined;\n this._min = undefined;\n this._size = 0;\n }\n\n add(element: E): boolean {\n this.push(element);\n return true;\n }\n\n /**\n * Push an element into the root list.\n * @remarks Time O(1) amortized, Space O(1)\n * @param element - Element to insert.\n * @returns This heap.\n */\n\n push(element: E): this {\n const node = this.createNode(element);\n node.left = node;\n node.right = node;\n this.mergeWithRoot(node);\n if (!this.min || this.comparator(node.element, this.min.element) <= 0) this._min = node;\n this._size++;\n return this;\n }\n\n peek(): E | undefined {\n return this.min ? this.min.element : undefined;\n }\n\n /**\n * Collect nodes from a circular doubly linked list starting at head.\n * @remarks Time O(K), Space O(K)\n * @param [head] - Start node of the circular list.\n * @returns Array of nodes from the list.\n */\n\n consumeLinkedList(head?: FibonacciHeapNode<E>): FibonacciHeapNode<E>[] {\n const elements: FibonacciHeapNode<E>[] = [];\n if (!head) return elements;\n let node: FibonacciHeapNode<E> | undefined = head;\n let started = false;\n while (true) {\n if (node === head && started) break;\n else if (node === head) started = true;\n elements.push(node!);\n node = node!.right;\n }\n return elements;\n }\n\n /**\n * Insert a node into a parent's child list (circular).\n * @remarks Time O(1), Space O(1)\n * @param parent - Parent node.\n * @param node - Child node to insert.\n * @returns void\n */\n\n mergeWithChild(parent: FibonacciHeapNode<E>, node: FibonacciHeapNode<E>): void {\n if (!parent.child) parent.child = node;\n else {\n node.right = parent.child.right;\n node.left = parent.child;\n parent.child.right!.left = node;\n parent.child.right = node;\n }\n }\n\n poll(): E | undefined {\n return this.pop();\n }\n\n /**\n * Remove and return the minimum element, consolidating the root list.\n * @remarks Time O(log N) amortized, Space O(1)\n * @returns Minimum element or undefined.\n */\n\n pop(): E | undefined {\n if (this._size === 0) return undefined;\n const z = this.min!;\n if (z.child) {\n const elements = this.consumeLinkedList(z.child);\n for (const node of elements) {\n this.mergeWithRoot(node);\n node.parent = undefined;\n }\n }\n this.removeFromRoot(z);\n if (z === z.right) {\n this._min = undefined;\n this._root = undefined;\n } else {\n this._min = z.right;\n this._consolidate();\n }\n this._size--;\n return z.element;\n }\n\n /**\n * Meld another heap into this heap.\n * @remarks Time O(1), Space O(1)\n * @param heapToMerge - Another FibonacciHeap to meld into this one.\n * @returns void\n */\n\n merge(heapToMerge: FibonacciHeap<E>): void {\n if (heapToMerge.size === 0) return;\n if (this.root && heapToMerge.root) {\n const thisRoot = this.root,\n otherRoot = heapToMerge.root;\n const thisRootRight = thisRoot.right!,\n otherRootLeft = otherRoot.left!;\n thisRoot.right = otherRoot;\n otherRoot.left = thisRoot;\n thisRootRight.left = otherRootLeft;\n otherRootLeft.right = thisRootRight;\n } else if (!this.root && heapToMerge.root) {\n this._root = heapToMerge.root;\n }\n if (!this.min || (heapToMerge.min && this.comparator(heapToMerge.min.element, this.min.element) < 0)) {\n this._min = heapToMerge.min;\n }\n this._size += heapToMerge.size;\n heapToMerge.clear();\n }\n\n createNode(element: E): FibonacciHeapNode<E> {\n return new FibonacciHeapNode<E>(element);\n }\n\n isEmpty(): boolean {\n return this._size === 0;\n }\n\n protected _defaultComparator(a: E, b: E): number {\n if (a < b) return -1;\n if (a > b) return 1;\n return 0;\n }\n\n protected mergeWithRoot(node: FibonacciHeapNode<E>): void {\n if (!this.root) this._root = node;\n else {\n node.right = this.root.right;\n node.left = this.root;\n this.root.right!.left = node;\n this.root.right = node;\n }\n }\n\n protected removeFromRoot(node: FibonacciHeapNode<E>): void {\n if (this.root === node) this._root = node.right;\n if (node.left) node.left.right = node.right;\n if (node.right) node.right.left = node.left;\n }\n\n protected _link(y: FibonacciHeapNode<E>, x: FibonacciHeapNode<E>): void {\n this.removeFromRoot(y);\n y.left = y;\n y.right = y;\n this.mergeWithChild(x, y);\n x.degree++;\n y.parent = x;\n }\n\n protected _consolidate(): void {\n const A: (FibonacciHeapNode<E> | undefined)[] = new Array(this._size);\n const elements = this.consumeLinkedList(this.root);\n let x: FibonacciHeapNode<E> | undefined,\n y: FibonacciHeapNode<E> | undefined,\n d: number,\n t: FibonacciHeapNode<E> | undefined;\n\n for (const node of elements) {\n x = node;\n d = x.degree;\n while (A[d]) {\n y = A[d] as FibonacciHeapNode<E>;\n if (this.comparator(x.element, y.element) > 0) {\n t = x;\n x = y;\n y = t;\n }\n this._link(y, x);\n A[d] = undefined;\n d++;\n }\n A[d] = x;\n }\n\n for (let i = 0; i < A.length; i++) {\n if (A[i] && (!this.min || this.comparator(A[i]!.element, this.min.element) <= 0)) this._min = A[i]!;\n }\n }\n}\n","import type { ElementCallback, LinearBaseOptions, ReduceLinearCallback } from '../../types';\nimport { IterableElementBase } from './iterable-element-base';\n\n/**\n * Singly-linked list node.\n * @template E - Element type.\n * @remarks Time O(1), Space O(1)\n */\nexport class LinkedListNode<E = any> {\n /**\n * Initialize a node.\n * @param value - Element value.\n * @remarks Time O(1), Space O(1)\n */\n constructor(value: E) {\n this._value = value;\n this._next = undefined;\n }\n\n protected _value: E;\n\n /**\n * Element payload getter.\n * @returns Element value.\n * @remarks Time O(1), Space O(1)\n */\n get value(): E {\n return this._value;\n }\n\n /**\n * Element payload setter.\n * @param value - New value.\n * @remarks Time O(1), Space O(1)\n */\n set value(value: E) {\n this._value = value;\n }\n\n protected _next: LinkedListNode<E> | undefined;\n\n /**\n * Next node getter.\n * @returns Next node or `undefined`.\n * @remarks Time O(1), Space O(1)\n */\n get next(): LinkedListNode<E> | undefined {\n return this._next;\n }\n\n /**\n * Next node setter.\n * @param value - Next node or `undefined`.\n * @remarks Time O(1), Space O(1)\n */\n set next(value: LinkedListNode<E> | undefined) {\n this._next = value;\n }\n}\n\n/**\n * Abstract linear container with array-like utilities.\n * @template E - Element type.\n * @template R - Return type for mapped/derived views.\n * @template NODE - Linked node type used by some implementations.\n * @remarks Time O(1), Space O(1)\n */\nexport abstract class LinearBase<\n E,\n R = any,\n NODE extends LinkedListNode<E> = LinkedListNode<E>\n> extends IterableElementBase<E, R> {\n /**\n * Construct a linear container with runtime options.\n * @param options - `{ maxLen?, ... }` bounds/behavior options.\n * @remarks Time O(1), Space O(1)\n */\n protected constructor(options?: LinearBaseOptions<E, R>) {\n super(options);\n if (options) {\n const { maxLen } = options;\n if (typeof maxLen === 'number' && maxLen > 0 && maxLen % 1 === 0) this._maxLen = maxLen;\n }\n }\n\n /**\n * Element count.\n * @returns Number of elements.\n * @remarks Time O(1), Space O(1)\n */\n abstract get length(): number;\n\n protected _maxLen: number = -1;\n\n /**\n * Upper bound for length (if positive), or `-1` when unbounded.\n * @returns Maximum allowed length.\n * @remarks Time O(1), Space O(1)\n */\n get maxLen() {\n return this._maxLen;\n }\n\n /**\n * First index of a value from the left.\n * @param searchElement - Value to match.\n * @param fromIndex - Start position (supports negative index).\n * @returns Index or `-1` if not found.\n * @remarks Time O(n), Space O(1)\n */\n indexOf(searchElement: E, fromIndex: number = 0): number {\n if (this.length === 0) return -1;\n if (fromIndex < 0) fromIndex = this.length + fromIndex;\n if (fromIndex < 0) fromIndex = 0;\n\n for (let i = fromIndex; i < this.length; i++) {\n const element = this.at(i);\n if (element === searchElement) return i;\n }\n\n return -1;\n }\n\n /**\n * Last index of a value from the right.\n * @param searchElement - Value to match.\n * @param fromIndex - Start position (supports negative index).\n * @returns Index or `-1` if not found.\n * @remarks Time O(n), Space O(1)\n */\n lastIndexOf(searchElement: E, fromIndex: number = this.length - 1): number {\n if (this.length === 0) return -1;\n if (fromIndex >= this.length) fromIndex = this.length - 1;\n if (fromIndex < 0) fromIndex = this.length + fromIndex;\n\n for (let i = fromIndex; i >= 0; i--) {\n const element = this.at(i);\n if (element === searchElement) return i;\n }\n\n return -1;\n }\n\n /**\n * Find the first index matching a predicate.\n * @param predicate - `(element, index, self) => boolean`.\n * @param thisArg - Optional `this` for callback.\n * @returns Index or `-1`.\n * @remarks Time O(n), Space O(1)\n */\n findIndex(predicate: ElementCallback<E, R, boolean>, thisArg?: any): number {\n for (let i = 0; i < this.length; i++) {\n const item = this.at(i);\n if (item !== undefined && predicate.call(thisArg, item, i, this)) return i;\n }\n return -1;\n }\n\n /**\n * Concatenate multiple containers of the same species.\n * @param items - Other lists to append.\n * @returns New container with combined elements (`this` type).\n * @remarks Time O(sum(length)), Space O(sum(length))\n */\n concat(...items: this[]): this;\n\n /**\n * Concatenate elements and/or containers.\n * @param items - Elements or other containers.\n * @returns New container with combined elements (`this` type).\n * @remarks Time O(sum(length)), Space O(sum(length))\n */\n concat(...items: (E | this)[]): this {\n const newList = this.clone();\n\n for (const item of items) {\n if (item instanceof LinearBase) {\n newList.pushMany(item);\n } else {\n newList.push(item);\n }\n }\n\n return newList;\n }\n\n /**\n * In-place stable order via array sort semantics.\n * @param compareFn - Comparator `(a, b) => number`.\n * @returns This container.\n * @remarks Time O(n log n), Space O(n) (materializes to array temporarily)\n */\n sort(compareFn?: (a: E, b: E) => number): this {\n const arr = this.toArray();\n arr.sort(compareFn);\n this.clear();\n for (const item of arr) this.push(item);\n return this;\n }\n\n /**\n * Remove and/or insert elements at a position (array-compatible).\n * @param start - Start index (supports negative index).\n * @param deleteCount - How many to remove.\n * @param items - Elements to insert.\n * @returns Removed elements as a new list (`this` type).\n * @remarks Time O(n + m), Space O(min(n, m)) where `m = items.length`\n */\n splice(start: number, deleteCount: number = 0, ...items: E[]): this {\n const removedList = this._createInstance();\n\n start = start < 0 ? this.length + start : start;\n start = Math.max(0, Math.min(start, this.length));\n deleteCount = Math.max(0, Math.min(deleteCount, this.length - start));\n\n for (let i = 0; i < deleteCount; i++) {\n const removed = this.deleteAt(start);\n if (removed !== undefined) {\n removedList.push(removed);\n }\n }\n\n for (let i = 0; i < items.length; i++) {\n this.addAt(start + i, items[i]);\n }\n\n return removedList;\n }\n\n /**\n * Join all elements into a string.\n * @param separator - Separator string.\n * @returns Concatenated string.\n * @remarks Time O(n), Space O(n)\n */\n join(separator: string = ','): string {\n return this.toArray().join(separator);\n }\n\n /**\n * Snapshot elements into a reversed array.\n * @returns New reversed array.\n * @remarks Time O(n), Space O(n)\n */\n toReversedArray(): E[] {\n const array: E[] = [];\n for (let i = this.length - 1; i >= 0; i--) {\n array.push(this.at(i)!);\n }\n return array;\n }\n\n reduceRight(callbackfn: ReduceLinearCallback<E>): E;\n\n reduceRight(callbackfn: ReduceLinearCallback<E>, initialValue: E): E;\n\n /**\n * Right-to-left reduction over elements.\n * @param callbackfn - `(acc, element, index, self) => acc`.\n * @param initialValue - Initial accumulator (optional generic overloads supported).\n * @returns Final accumulator.\n * @remarks Time O(n), Space O(1)\n */\n reduceRight<U>(callbackfn: ReduceLinearCallback<E, U>, initialValue: U): U;\n\n reduceRight<U>(callbackfn: ReduceLinearCallback<E, U>, initialValue?: U): U {\n let accumulator = initialValue ?? (0 as U);\n for (let i = this.length - 1; i >= 0; i--) {\n accumulator = callbackfn(accumulator, this.at(i)!, i, this);\n }\n return accumulator;\n }\n\n /**\n * Create a shallow copy of a subrange.\n * @param start - Inclusive start (supports negative index).\n * @param end - Exclusive end (supports negative index).\n * @returns New list with the range (`this` type).\n * @remarks Time O(n), Space O(n)\n */\n slice(start: number = 0, end: number = this.length): this {\n start = start < 0 ? this.length + start : start;\n end = end < 0 ? this.length + end : end;\n\n const newList = this._createInstance();\n for (let i = start; i < end; i++) {\n newList.push(this.at(i)!);\n }\n return newList;\n }\n\n /**\n * Fill a range with a value.\n * @param value - Value to set.\n * @param start - Inclusive start.\n * @param end - Exclusive end.\n * @returns This list.\n * @remarks Time O(n), Space O(1)\n */\n fill(value: E, start = 0, end = this.length): this {\n start = start < 0 ? this.length + start : start;\n end = end < 0 ? this.length + end : end;\n\n if (start < 0) start = 0;\n if (end > this.length) end = this.length;\n if (start >= end) return this;\n\n for (let i = start; i < end; i++) {\n this.setAt(i, value);\n }\n\n return this;\n }\n\n /**\n * Set the value at an index.\n * @param index - Position (0-based).\n * @param value - New value.\n * @returns `true` if updated.\n * @remarks Time O(1) typical, Space O(1)\n */\n abstract setAt(index: number, value: E): boolean;\n\n /**\n * Deep clone while preserving concrete subtype.\n * @returns New list of the same species (`this` type).\n * @remarks Time O(n), Space O(n)\n */\n abstract override clone(): this;\n\n /**\n * Reverse the order of elements in-place (or equivalent).\n * @returns This list.\n * @remarks Time O(n), Space O(1)\n */\n abstract reverse(): this;\n\n /**\n * Append one element or node to the tail.\n * @param elementOrNode - Element or node.\n * @returns `true` if appended.\n * @remarks Time O(1) amortized typical, Space O(1)\n */\n abstract push(elementOrNode: E | NODE): boolean;\n\n /**\n * Append many elements/nodes at once.\n * @param elements - Iterable of elements or nodes.\n * @returns Array of booleans indicating append success.\n * @remarks Time O(n), Space O(1)\n */\n abstract pushMany(elements: Iterable<E> | Iterable<R> | Iterable<NODE>): boolean[];\n\n /**\n * Remove one element or node if present.\n * @param elementOrNode - Element or node to delete.\n * @returns `true` if removed.\n * @remarks Time O(1)~O(n) depending on implementation, Space O(1)\n */\n abstract delete(elementOrNode: E | NODE | undefined): boolean;\n\n /**\n * Get element at an index.\n * @param index - Position (0-based).\n * @returns Element or `undefined`.\n * @remarks Time O(1)~O(n) depending on implementation, Space O(1)\n */\n abstract at(index: number): E | undefined;\n\n /**\n * Remove element at a position.\n * @param pos - Position (0-based).\n * @returns Removed element or `undefined`.\n * @remarks Time O(1)~O(n) depending on implementation, Space O(1)\n */\n abstract deleteAt(pos: number): E | undefined;\n\n /**\n * Insert an element/node at a position.\n * @param index - Position (0-based).\n * @param newElementOrNode - Element or node to insert.\n * @returns `true` if inserted.\n * @remarks Time O(1)~O(n) depending on implementation, Space O(1)\n */\n abstract addAt(index: number, newElementOrNode: E | NODE): boolean;\n\n /**\n * Create an empty list of the same species.\n * @param options - Runtime options to carry.\n * @returns Empty list (`this` type).\n * @remarks Time O(1), Space O(1)\n */\n protected abstract _createInstance(options?: LinearBaseOptions<E, R>): this;\n\n /**\n * Reverse-direction iterator over elements.\n * @returns Iterator of elements from tail to head.\n * @remarks Time O(n), Space O(1)\n */\n protected abstract _getReverseIterator(...args: any[]): IterableIterator<E>;\n}\n\n/**\n * Linked-list specialized linear container.\n * @template E - Element type.\n * @template R - Return type for mapped/derived views.\n * @template NODE - Linked node type.\n * @remarks Time O(1), Space O(1)\n */\nexport abstract class LinearLinkedBase<\n E,\n R = any,\n NODE extends LinkedListNode<E> = LinkedListNode<E>\n> extends LinearBase<E, R, NODE> {\n protected constructor(options?: LinearBaseOptions<E, R>) {\n super(options);\n if (options) {\n const { maxLen } = options;\n if (typeof maxLen === 'number' && maxLen > 0 && maxLen % 1 === 0) this._maxLen = maxLen;\n }\n }\n\n /**\n * Linked-list optimized `indexOf` (forwards scan).\n * @param searchElement - Value to match.\n * @param fromIndex - Start position.\n * @returns Index or `-1`.\n * @remarks Time O(n), Space O(1)\n */\n override indexOf(searchElement: E, fromIndex: number = 0): number {\n const iterator = this._getIterator();\n let current = iterator.next();\n\n let index = 0;\n while (index < fromIndex) {\n current = iterator.next();\n index++;\n }\n\n while (!current.done) {\n if (current.value === searchElement) return index;\n current = iterator.next();\n index++;\n }\n\n return -1;\n }\n\n /**\n * Linked-list optimized `lastIndexOf` (reverse scan).\n * @param searchElement - Value to match.\n * @param fromIndex - Start position.\n * @returns Index or `-1`.\n * @remarks Time O(n), Space O(1)\n */\n override lastIndexOf(searchElement: E, fromIndex: number = this.length - 1): number {\n const iterator = this._getReverseIterator();\n let current = iterator.next();\n\n let index = this.length - 1;\n while (index > fromIndex) {\n current = iterator.next();\n index--;\n }\n\n while (!current.done) {\n if (current.value === searchElement) return index;\n current = iterator.next();\n index--;\n }\n\n return -1;\n }\n\n /**\n * Concatenate lists/elements preserving order.\n * @param items - Elements or `LinearBase` instances.\n * @returns New list with combined elements (`this` type).\n * @remarks Time O(sum(length)), Space O(sum(length))\n */\n override concat(...items: LinearBase<E, R>[]): this;\n\n override concat(...items: (E | LinearBase<E, R>)[]): this {\n const newList = this.clone();\n\n for (const item of items) {\n if (item instanceof LinearBase) {\n newList.pushMany(item);\n } else {\n newList.push(item);\n }\n }\n\n return newList;\n }\n\n /**\n * Slice via forward iteration (no random access required).\n * @param start - Inclusive start (supports negative index).\n * @param end - Exclusive end (supports negative index).\n * @returns New list (`this` type).\n * @remarks Time O(n), Space O(n)\n */\n override slice(start: number = 0, end: number = this.length): this {\n start = start < 0 ? this.length + start : start;\n end = end < 0 ? this.length + end : end;\n\n const newList = this._createInstance();\n const iterator = this._getIterator();\n let current = iterator.next();\n let c = 0;\n while (c < start) {\n current = iterator.next();\n c++;\n }\n for (let i = start; i < end; i++) {\n newList.push(current.value);\n current = iterator.next();\n }\n\n return newList;\n }\n\n /**\n * Splice by walking node iterators from the start index.\n * @param start - Start index.\n * @param deleteCount - How many elements to remove.\n * @param items - Elements to insert after the splice point.\n * @returns Removed elements as a new list (`this` type).\n * @remarks Time O(n + m), Space O(min(n, m)) where `m = items.length`\n */\n override splice(start: number, deleteCount: number = 0, ...items: E[]): this {\n const removedList = this._createInstance();\n\n start = start < 0 ? this.length + start : start;\n start = Math.max(0, Math.min(start, this.length));\n deleteCount = Math.max(0, deleteCount);\n\n let currentIndex = 0;\n let currentNode: NODE | undefined = undefined;\n let previousNode: NODE | undefined = undefined;\n\n const iterator = this._getNodeIterator();\n for (const node of iterator) {\n if (currentIndex === start) {\n currentNode = node;\n break;\n }\n previousNode = node;\n currentIndex++;\n }\n\n for (let i = 0; i < deleteCount && currentNode; i++) {\n removedList.push(currentNode.value);\n const nextNode = currentNode.next;\n this.delete(currentNode);\n currentNode = nextNode as NODE;\n }\n\n for (let i = 0; i < items.length; i++) {\n if (previousNode) {\n this.addAfter(previousNode, items[i]);\n previousNode = previousNode.next as NODE;\n } else {\n this.addAt(0, items[i]);\n previousNode = this._getNodeIterator().next().value;\n }\n }\n\n return removedList;\n }\n\n override reduceRight(callbackfn: ReduceLinearCallback<E>): E;\n\n override reduceRight(callbackfn: ReduceLinearCallback<E>, initialValue: E): E;\n\n /**\n * Right-to-left reduction using reverse iterator.\n * @param callbackfn - `(acc, element, index, self) => acc`.\n * @param initialValue - Initial accumulator.\n * @returns Final accumulator.\n * @remarks Time O(n), Space O(1)\n */\n override reduceRight<U>(callbackfn: ReduceLinearCallback<E, U>, initialValue: U): U;\n\n override reduceRight<U>(callbackfn: ReduceLinearCallback<E, U>, initialValue?: U): U {\n let accumulator = initialValue ?? (0 as U);\n let index = this.length - 1;\n for (const item of this._getReverseIterator()) {\n accumulator = callbackfn(accumulator, item, index--, this);\n }\n return accumulator;\n }\n\n /**\n * Delete by element or node in a linked list.\n * @param elementOrNode - Element or node.\n * @returns `true` if removed.\n * @remarks Time O(1)~O(n) depending on availability of links, Space O(1)\n */\n abstract override delete(elementOrNode: E | NODE | undefined): boolean;\n\n /**\n * Insert new element/node before an existing node.\n * @param existingElementOrNode - Reference element/node.\n * @param newElementOrNode - Element/node to insert.\n * @returns `true` if inserted.\n * @remarks Time O(1)~O(n) depending on reference access, Space O(1)\n */\n abstract addBefore(existingElementOrNode: E | NODE, newElementOrNode: E | NODE): boolean;\n\n /**\n * Insert new element/node after an existing node.\n * @param existingElementOrNode - Reference element/node.\n * @param newElementOrNode - Element/node to insert.\n * @returns `true` if inserted.\n * @remarks Time O(1)~O(n) depending on reference access, Space O(1)\n */\n abstract addAfter(existingElementOrNode: E | NODE, newElementOrNode: E | NODE): boolean;\n\n /**\n * Node at index (for random-access emulation).\n * @param index - Position (0-based).\n * @returns Node or `undefined`.\n * @remarks Time O(n), Space O(1)\n */\n abstract getNodeAt(index: number): NODE | undefined;\n\n /**\n * Iterate linked nodes from head to tail.\n * @returns Iterator over nodes.\n * @remarks Time O(n), Space O(1)\n */\n protected abstract _getNodeIterator(...args: any[]): IterableIterator<NODE>;\n\n /**\n * Get previous node of a given node.\n * @param node - Current node.\n * @returns Previous node or `undefined`.\n * @remarks Time O(1)~O(n) depending on list variant (singly vs doubly), Space O(1)\n */\n protected abstract _getPrevNode(node: NODE): NODE | undefined;\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type { ElementCallback, LinearBaseOptions, QueueOptions } from '../../types';\nimport { SinglyLinkedList } from '../linked-list';\nimport { LinearBase } from '../base/linear-base';\n\n/**\n * Array-backed queue with amortized O(1) enqueue/dequeue via an offset pointer and optional auto-compaction.\n * @remarks Time O(1), Space O(1)\n * @template E\n * @template R\n * 1. First In, First Out (FIFO): The core feature of a queue is its first in, first out nature. The element added to the queue first will be the one to be removed first.\n * 2. Operations: The main operations include enqueue (adding an element to the end of the queue) and dequeue (removing and returning the element at the front of the queue). Typically, there is also a peek operation (looking at the front element without removing it).\n * 3. Uses: Queues are commonly used to manage a series of tasks or elements that need to be processed in order. For example, managing task queues in a multi-threaded environment, or in algorithms for data structures like trees and graphs for breadth-first search.\n * 4. Task Scheduling: Managing the order of task execution in operating systems or applications.\n * 5. Data Buffering: Acting as a buffer for data packets in network communication.\n * 6. Breadth-First Search (BFS): In traversal algorithms for graphs and trees, queues store elements that are to be visited.\n * 7. Real-time Queuing: Like queuing systems in banks or supermarkets.\n * @example\n * // Sliding Window using Queue\n * const nums = [2, 3, 4, 1, 5];\n * const k = 2;\n * const queue = new Queue<number>();\n *\n * let maxSum = 0;\n * let currentSum = 0;\n *\n * nums.forEach(num => {\n * queue.push(num);\n * currentSum += num;\n *\n * if (queue.length > k) {\n * currentSum -= queue.shift()!;\n * }\n *\n * if (queue.length === k) {\n * maxSum = Math.max(maxSum, currentSum);\n * }\n * });\n *\n * console.log(maxSum); // 7\n * @example\n * // Breadth-First Search (BFS) using Queue\n * const graph: { [key in number]: number[] } = {\n * 1: [2, 3],\n * 2: [4, 5],\n * 3: [],\n * 4: [],\n * 5: []\n * };\n *\n * const queue = new Queue<number>();\n * const visited: number[] = [];\n *\n * queue.push(1);\n *\n * while (!queue.isEmpty()) {\n * const node = queue.shift()!;\n * if (!visited.includes(node)) {\n * visited.push(node);\n * graph[node].forEach(neighbor => queue.push(neighbor));\n * }\n * }\n *\n * console.log(visited); // [1, 2, 3, 4, 5]\n */\nexport class Queue<E = any, R = any> extends LinearBase<E, R> {\n /**\n * Create a Queue and optionally bulk-insert elements.\n * @remarks Time O(N), Space O(N)\n * @param [elements] - Iterable of elements (or raw records if toElementFn is set).\n * @param [options] - Options such as toElementFn, maxLen, and autoCompactRatio.\n * @returns New Queue instance.\n */\n\n constructor(elements: Iterable<E> | Iterable<R> = [], options?: QueueOptions<E, R>) {\n super(options);\n if (options) {\n const { autoCompactRatio = 0.5 } = options;\n this._autoCompactRatio = autoCompactRatio;\n }\n this.pushMany(elements);\n }\n\n protected _elements: E[] = [];\n\n /**\n * Get the underlying array buffer.\n * @remarks Time O(1), Space O(1)\n * @returns Backing array of elements.\n */\n\n get elements(): E[] {\n return this._elements;\n }\n\n protected _offset = 0;\n\n /**\n * Get the current start offset into the array.\n * @remarks Time O(1), Space O(1)\n * @returns Zero-based offset.\n */\n\n get offset(): number {\n return this._offset;\n }\n\n protected _autoCompactRatio = 0.5;\n\n /**\n * Get the compaction threshold (offset/size).\n * @remarks Time O(1), Space O(1)\n * @returns Auto-compaction ratio in (0,1].\n */\n\n get autoCompactRatio(): number {\n return this._autoCompactRatio;\n }\n\n /**\n * Set the compaction threshold.\n * @remarks Time O(1), Space O(1)\n * @param value - New ratio; compacts when offset/size exceeds this value.\n * @returns void\n */\n\n set autoCompactRatio(value: number) {\n this._autoCompactRatio = value;\n }\n\n /**\n * Get the number of elements currently in the queue.\n * @remarks Time O(1), Space O(1)\n * @returns Current length.\n */\n\n get length(): number {\n return this.elements.length - this._offset;\n }\n\n /**\n * Get the first element (front) without removing it.\n * @remarks Time O(1), Space O(1)\n * @returns Front element or undefined.\n */\n\n get first(): E | undefined {\n return this.length > 0 ? this.elements[this._offset] : undefined;\n }\n\n /**\n * Get the last element (back) without removing it.\n * @remarks Time O(1), Space O(1)\n * @returns Back element or undefined.\n */\n\n get last(): E | undefined {\n return this.length > 0 ? this.elements[this.elements.length - 1] : undefined;\n }\n\n /**\n * Create a queue from an array of elements.\n * @remarks Time O(N), Space O(N)\n * @template E\n * @param elements - Array of elements to enqueue in order.\n * @returns A new queue populated from the array.\n */\n\n static fromArray<E>(elements: E[]): Queue<E> {\n return new Queue(elements);\n }\n\n /**\n * Check whether the queue is empty.\n * @remarks Time O(1), Space O(1)\n * @returns True if length is 0.\n */\n\n isEmpty(): boolean {\n return this.length === 0;\n }\n\n /**\n * Enqueue one element at the back.\n * @remarks Time O(1), Space O(1)\n * @param element - Element to enqueue.\n * @returns True on success.\n */\n\n push(element: E): boolean {\n this.elements.push(element);\n if (this._maxLen > 0 && this.length > this._maxLen) this.shift();\n return true;\n }\n\n /**\n * Enqueue many elements from an iterable.\n * @remarks Time O(N), Space O(1)\n * @param elements - Iterable of elements (or raw records if toElementFn is set).\n * @returns Array of per-element success flags.\n */\n\n pushMany(elements: Iterable<E> | Iterable<R>): boolean[] {\n const ans: boolean[] = [];\n for (const el of elements) {\n if (this.toElementFn) ans.push(this.push(this.toElementFn(el as R)));\n else ans.push(this.push(el as E));\n }\n return ans;\n }\n\n /**\n * Dequeue one element from the front (amortized via offset).\n * @remarks Time O(1) amortized, Space O(1)\n * @returns Removed element or undefined.\n */\n\n shift(): E | undefined {\n if (this.length === 0) return undefined;\n const first = this.first;\n this._offset += 1;\n if (this.elements.length > 0 && this.offset / this.elements.length > this.autoCompactRatio) this.compact();\n return first;\n }\n\n /**\n * Delete the first occurrence of a specific element.\n * @remarks Time O(N), Space O(1)\n * @param element - Element to remove (strict equality via Object.is).\n * @returns True if an element was removed.\n */\n\n delete(element: E): boolean {\n for (let i = this._offset; i < this.elements.length; i++) {\n if (Object.is(this.elements[i], element)) {\n this.elements.splice(i, 1);\n return true;\n }\n }\n return false;\n }\n\n /**\n * Get the element at a given logical index.\n * @remarks Time O(1), Space O(1)\n * @param index - Zero-based index from the front.\n * @returns Element or undefined.\n */\n\n at(index: number): E | undefined {\n if (index < 0 || index >= this.length) return undefined;\n return this._elements[this._offset + index];\n }\n\n /**\n * Delete the element at a given index.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index from the front.\n * @returns Removed element or undefined.\n */\n\n deleteAt(index: number): E | undefined {\n if (index < 0 || index >= this.length) return undefined;\n const gi = this._offset + index;\n const [deleted] = this.elements.splice(gi, 1);\n return deleted;\n }\n\n /**\n * Insert a new element at a given index.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index from the front.\n * @param newElement - Element to insert.\n * @returns True if inserted.\n */\n\n addAt(index: number, newElement: E): boolean {\n if (index < 0 || index > this.length) return false;\n this._elements.splice(this._offset + index, 0, newElement);\n return true;\n }\n\n /**\n * Replace the element at a given index.\n * @remarks Time O(1), Space O(1)\n * @param index - Zero-based index from the front.\n * @param newElement - New element to set.\n * @returns True if updated.\n */\n\n setAt(index: number, newElement: E): boolean {\n if (index < 0 || index >= this.length) return false;\n this._elements[this._offset + index] = newElement;\n return true;\n }\n\n /**\n * Reverse the queue in-place by compacting then reversing.\n * @remarks Time O(N), Space O(N)\n * @returns This queue.\n */\n\n reverse(): this {\n this._elements = this.elements.slice(this._offset).reverse();\n this._offset = 0;\n return this;\n }\n\n /**\n * Remove all elements and reset offset.\n * @remarks Time O(1), Space O(1)\n * @returns void\n */\n\n clear(): void {\n this._elements = [];\n this._offset = 0;\n }\n\n /**\n * Compact storage by discarding consumed head elements.\n * @remarks Time O(N), Space O(N)\n * @returns True when compaction performed.\n */\n\n compact(): boolean {\n this._elements = this.elements.slice(this._offset);\n this._offset = 0;\n return true;\n }\n\n /**\n * Remove and/or insert elements at a position (array-like).\n * @remarks Time O(N + M), Space O(M)\n * @param start - Start index (clamped to [0, length]).\n * @param [deleteCount] - Number of elements to remove (default 0).\n * @param [items] - Elements to insert after `start`.\n * @returns A new queue containing the removed elements (typed as `this`).\n */\n\n override splice(start: number, deleteCount: number = 0, ...items: E[]): this {\n start = Math.max(0, Math.min(start, this.length));\n deleteCount = Math.max(0, Math.min(deleteCount, this.length - start));\n\n const gi = this._offset + start;\n const removedArray = this._elements.splice(gi, deleteCount, ...items);\n\n if (this.elements.length > 0 && this.offset / this.elements.length > this.autoCompactRatio) this.compact();\n\n const removed = this._createInstance({ toElementFn: this.toElementFn, maxLen: this._maxLen });\n removed._setAutoCompactRatio(this._autoCompactRatio);\n removed.pushMany(removedArray);\n\n return removed as unknown as this;\n }\n\n /**\n * Deep clone this queue and its parameters.\n * @remarks Time O(N), Space O(N)\n * @returns A new queue with the same content and options.\n */\n\n clone(): this {\n const out = this._createInstance({ toElementFn: this.toElementFn, maxLen: this._maxLen });\n out._setAutoCompactRatio(this._autoCompactRatio);\n for (let i = this._offset; i < this.elements.length; i++) out.push(this.elements[i]);\n return out;\n }\n\n /**\n * Filter elements into a new queue of the same class.\n * @remarks Time O(N), Space O(N)\n * @param predicate - Predicate (element, index, queue) → boolean to keep element.\n * @param [thisArg] - Value for `this` inside the predicate.\n * @returns A new queue with kept elements.\n */\n\n filter(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): this {\n const out = this._createInstance({ toElementFn: this.toElementFn, maxLen: this._maxLen });\n out._setAutoCompactRatio(this._autoCompactRatio);\n let index = 0;\n for (const v of this) {\n if (predicate.call(thisArg, v, index, this)) out.push(v);\n index++;\n }\n return out;\n }\n\n /**\n * Map each element to a new element in a possibly different-typed queue.\n * @remarks Time O(N), Space O(N)\n * @template EM\n * @template RM\n * @param callback - Mapping function (element, index, queue) → newElement.\n * @param [options] - Options for the output queue (e.g., toElementFn, maxLen, autoCompactRatio).\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new Queue with mapped elements.\n */\n\n map<EM, RM>(callback: ElementCallback<E, R, EM>, options?: QueueOptions<EM, RM>, thisArg?: unknown): Queue<EM, RM> {\n const out = new (this.constructor as new (\n elements?: Iterable<EM> | Iterable<RM>,\n options?: QueueOptions<EM, RM>\n ) => Queue<EM, RM>)([], {\n toElementFn: options?.toElementFn,\n maxLen: options?.maxLen ?? this._maxLen,\n autoCompactRatio: options?.autoCompactRatio ?? this._autoCompactRatio\n });\n let index = 0;\n for (const v of this)\n out.push(thisArg === undefined ? callback(v, index++, this) : callback.call(thisArg, v, index++, this));\n return out;\n }\n\n /**\n * Map each element to a new value of the same type.\n * @remarks Time O(N), Space O(N)\n * @param callback - Mapping function (element, index, queue) → element.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new queue with mapped elements (same element type).\n */\n\n mapSame(callback: ElementCallback<E, R, E>, thisArg?: unknown): this {\n const Ctor = this.constructor as new (\n elements?: Iterable<E> | Iterable<R>,\n options?: QueueOptions<E, R>\n ) => Queue<E, R>;\n const out = new Ctor([], {\n toElementFn: this.toElementFn,\n maxLen: this._maxLen,\n autoCompactRatio: this._autoCompactRatio\n });\n out._setAutoCompactRatio?.(this._autoCompactRatio);\n let index = 0;\n for (const v of this) {\n const mv = thisArg === undefined ? callback(v, index++, this) : callback.call(thisArg, v, index++, this);\n out.push(mv);\n }\n return out as this;\n }\n\n /**\n * (Protected) Set the internal auto-compaction ratio.\n * @remarks Time O(1), Space O(1)\n * @param value - New ratio to assign.\n * @returns void\n */\n\n protected _setAutoCompactRatio(value: number): void {\n this._autoCompactRatio = value;\n }\n\n /**\n * (Protected) Iterate elements from front to back.\n * @remarks Time O(N), Space O(1)\n * @returns Iterator of E.\n */\n\n protected *_getIterator(): IterableIterator<E> {\n for (let i = this._offset; i < this.elements.length; i++) yield this.elements[i];\n }\n\n /**\n * (Protected) Iterate elements from back to front.\n * @remarks Time O(N), Space O(1)\n * @returns Iterator of E.\n */\n\n protected *_getReverseIterator(): IterableIterator<E> {\n for (let i = this.length - 1; i >= 0; i--) {\n const cur = this.at(i);\n if (cur !== undefined) yield cur;\n }\n }\n\n /**\n * (Protected) Create an empty instance of the same concrete class.\n * @remarks Time O(1), Space O(1)\n * @param [options] - Options forwarded to the constructor.\n * @returns An empty like-kind queue instance.\n */\n\n protected override _createInstance(options?: LinearBaseOptions<E, R>): this {\n const Ctor = this.constructor as new (elements?: Iterable<E> | Iterable<R>, options?: QueueOptions<E, R>) => this;\n return new Ctor([], options as QueueOptions<E, R> | undefined);\n }\n\n /**\n * (Protected) Create a like-kind queue and seed it from an iterable.\n * @remarks Time O(N), Space O(N)\n * @template EM\n * @template RM\n * @param [elements] - Iterable used to seed the new queue.\n * @param [options] - Options forwarded to the constructor.\n * @returns A like-kind Queue instance.\n */\n\n protected _createLike<EM = E, RM = R>(\n elements: Iterable<EM> | Iterable<RM> = [],\n options?: QueueOptions<EM, RM>\n ): Queue<EM, RM> {\n const Ctor = this.constructor as new (\n elements?: Iterable<EM> | Iterable<RM>,\n options?: QueueOptions<EM, RM>\n ) => Queue<EM, RM>;\n return new Ctor(elements, options);\n }\n}\n\n/**\n * Queue implemented over a singly linked list; preserves head/tail operations with linear scans for queries.\n * @remarks Time O(1), Space O(1)\n * @template E\n * @template R\n * @example examples will be generated by unit test\n */\nexport class LinkedListQueue<E = any, R = any> extends SinglyLinkedList<E, R> {\n /**\n * Deep clone this linked-list-based queue.\n * @remarks Time O(N), Space O(N)\n * @returns A new queue with the same sequence of elements.\n */\n\n override clone(): this {\n const out = this._createInstance({ toElementFn: this.toElementFn, maxLen: this._maxLen });\n for (const v of this) out.push(v);\n return out;\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type { DijkstraResult, EntryCallback, GraphOptions, VertexKey } from '../../types';\nimport { uuidV4 } from '../../utils';\nimport { IterableEntryBase } from '../base';\nimport { IGraph } from '../../interfaces';\nimport { Heap } from '../heap';\nimport { Queue } from '../queue';\n\nexport abstract class AbstractVertex<V = any> {\n key: VertexKey;\n value: V | undefined;\n\n protected constructor(key: VertexKey, value?: V) {\n this.key = key;\n this.value = value;\n }\n}\n\nexport abstract class AbstractEdge<E = any> {\n value: E | undefined;\n weight: number;\n\n protected constructor(weight?: number, value?: E) {\n this.weight = weight !== undefined ? weight : 1;\n this.value = value;\n this._hashCode = uuidV4();\n }\n\n protected _hashCode: string;\n\n get hashCode(): string {\n return this._hashCode;\n }\n}\n\n/**\n * Abstract graph over vertices and edges.\n * @template V - Vertex value type.\n * @template E - Edge value type.\n * @template VO - Concrete vertex subclass (extends AbstractVertex<V>).\n * @template EO - Concrete edge subclass (extends AbstractEdge<E>).\n * @remarks Time O(1), Space O(1)\n * @example examples will be generated by unit test\n */\nexport abstract class AbstractGraph<\n V = any,\n E = any,\n VO extends AbstractVertex<V> = AbstractVertex<V>,\n EO extends AbstractEdge<E> = AbstractEdge<E>\n >\n extends IterableEntryBase<VertexKey, V | undefined>\n implements IGraph<V, E, VO, EO>\n{\n /**\n * Construct a graph with runtime defaults.\n * @param options - `GraphOptions<V>` in `options.graph` (e.g. `vertexValueInitializer`, `defaultEdgeWeight`).\n * @remarks Time O(1), Space O(1)\n */\n constructor(options?: Partial<Record<string, unknown>>) {\n super();\n const graph = (options as any)?.graph as GraphOptions<V> | undefined;\n this._options = { defaultEdgeWeight: 1, ...(graph ?? {}) };\n }\n\n protected _options: GraphOptions<V> = { defaultEdgeWeight: 1 };\n\n get options(): Readonly<GraphOptions<V>> {\n return this._options;\n }\n\n protected _vertexMap: Map<VertexKey, VO> = new Map<VertexKey, VO>();\n\n get vertexMap(): Map<VertexKey, VO> {\n return this._vertexMap;\n }\n\n set vertexMap(v: Map<VertexKey, VO>) {\n this._vertexMap = v;\n }\n\n get size(): number {\n return this._vertexMap.size;\n }\n\n /**\n * Create a new vertex instance (implementation specific).\n * @param key - Vertex identifier.\n * @param value - Optional payload.\n * @returns Concrete vertex instance.\n * @remarks Time O(1), Space O(1)\n */\n abstract createVertex(key: VertexKey, value?: V): VO;\n\n /**\n * Create a new edge instance (implementation specific).\n * @param srcOrV1 - Source/endpoint A key.\n * @param destOrV2 - Destination/endpoint B key.\n * @param weight - Edge weight (defaults may apply).\n * @param value - Edge payload.\n * @returns Concrete edge instance.\n * @remarks Time O(1), Space O(1)\n */\n abstract createEdge(srcOrV1: VertexKey, destOrV2: VertexKey, weight?: number, value?: E): EO;\n\n /**\n * Delete an edge by instance.\n * @param edge - Edge instance.\n * @returns Removed edge or `undefined`.\n * @remarks Time O(1) avg, Space O(1)\n */\n abstract deleteEdge(edge: EO): EO | undefined;\n\n /**\n * Get an edge between two vertices if present.\n * @param srcOrKey - Source/endpoint A vertex or key.\n * @param destOrKey - Destination/endpoint B vertex or key.\n * @returns Edge instance or `undefined`.\n * @remarks Time O(1) avg, Space O(1)\n */\n abstract getEdge(srcOrKey: VO | VertexKey, destOrKey: VO | VertexKey): EO | undefined;\n\n /**\n * Degree of a vertex in this graph model.\n * @param vertexOrKey - Vertex or key.\n * @returns Non-negative integer degree.\n * @remarks Time O(1) avg, Space O(1)\n */\n abstract degreeOf(vertexOrKey: VO | VertexKey): number;\n\n /**\n * All edges in the graph (unique, order not guaranteed).\n * @returns Array of edges.\n * @remarks Time O(E), Space O(E)\n */\n abstract edgeSet(): EO[];\n\n /**\n * Incident edges of a vertex.\n * @param vertexOrKey - Vertex or key.\n * @returns Array of incident edges.\n * @remarks Time O(deg), Space O(deg)\n */\n abstract edgesOf(vertexOrKey: VO | VertexKey): EO[];\n\n /**\n * One-step neighbors of a vertex.\n * @param vertexOrKey - Vertex or key.\n * @returns Array of neighbor vertices.\n * @remarks Time O(deg), Space O(deg)\n */\n abstract getNeighbors(vertexOrKey: VO | VertexKey): VO[];\n\n /**\n * Resolve endpoints of an edge to vertex instances.\n * @param edge - Edge instance.\n * @returns `[v1, v2]` or `undefined` if missing.\n * @remarks Time O(1), Space O(1)\n */\n abstract getEndsOfEdge(edge: EO): [VO, VO] | undefined;\n\n /**\n * Get vertex instance by key.\n * @param vertexKey - Vertex key.\n * @returns Vertex instance or `undefined`.\n * @remarks Time O(1), Space O(1)\n */\n getVertex(vertexKey: VertexKey): VO | undefined {\n return this._vertexMap.get(vertexKey) || undefined;\n }\n\n /**\n * Whether a vertex exists.\n * @param vertexOrKey - Vertex or key.\n * @returns `true` if present, otherwise `false`.\n * @remarks Time O(1) avg, Space O(1)\n */\n hasVertex(vertexOrKey: VO | VertexKey): boolean {\n return this._vertexMap.has(this._getVertexKey(vertexOrKey));\n }\n\n addVertex(vertex: VO): boolean;\n\n addVertex(key: VertexKey, value?: V): boolean;\n\n /**\n * Add a vertex by key/value or by pre-built vertex.\n * @param keyOrVertex - Vertex key or existing vertex instance.\n * @param value - Optional payload.\n * @returns `true` if inserted; `false` when key already exists.\n * @remarks Time O(1) avg, Space O(1)\n */\n addVertex(keyOrVertex: VertexKey | VO, value?: V): boolean {\n if (keyOrVertex instanceof AbstractVertex) {\n return this._addVertex(keyOrVertex);\n } else {\n const newVertex = this.createVertex(keyOrVertex, value);\n return this._addVertex(newVertex);\n }\n }\n\n /**\n * Type guard: check if a value is a valid vertex key.\n * @param potentialKey - Value to test.\n * @returns `true` if string/number; else `false`.\n * @remarks Time O(1), Space O(1)\n */\n isVertexKey(potentialKey: any): potentialKey is VertexKey {\n const potentialKeyType = typeof potentialKey;\n return potentialKeyType === 'string' || potentialKeyType === 'number';\n }\n\n /**\n * Delete a vertex and its incident edges.\n * @param vertexOrKey - Vertex or key.\n * @returns `true` if removed; otherwise `false`.\n * @remarks Time O(deg), Space O(1)\n */\n abstract deleteVertex(vertexOrKey: VO | VertexKey): boolean;\n\n /**\n * Delete multiple vertices.\n * @param vertexMap - Array of vertices or keys.\n * @returns `true` if any vertex was removed.\n * @remarks Time O(sum(deg)), Space O(1)\n */\n removeManyVertices(vertexMap: VO[] | VertexKey[]): boolean {\n const removed: boolean[] = [];\n for (const v of vertexMap) {\n removed.push(this.deleteVertex(v));\n }\n return removed.length > 0;\n }\n\n /**\n * Whether an edge exists between two vertices.\n * @param v1 - Endpoint A vertex or key.\n * @param v2 - Endpoint B vertex or key.\n * @returns `true` if present; otherwise `false`.\n * @remarks Time O(1) avg, Space O(1)\n */\n hasEdge(v1: VertexKey | VO, v2: VertexKey | VO): boolean {\n const edge = this.getEdge(v1, v2);\n return !!edge;\n }\n\n addEdge(edge: EO): boolean;\n\n addEdge(src: VO | VertexKey, dest: VO | VertexKey, weight?: number, value?: E): boolean;\n\n /**\n * Add an edge by instance or by `(src, dest, weight?, value?)`.\n * @param srcOrEdge - Edge instance or source vertex/key.\n * @param dest - Destination vertex/key (when adding by pair).\n * @param weight - Edge weight.\n * @param value - Edge payload.\n * @returns `true` if inserted; otherwise `false`.\n * @remarks Time O(1) avg, Space O(1)\n */\n addEdge(srcOrEdge: VO | VertexKey | EO, dest?: VO | VertexKey, weight?: number, value?: E): boolean {\n if (srcOrEdge instanceof AbstractEdge) {\n return this._addEdge(srcOrEdge);\n } else {\n if (dest instanceof AbstractVertex || typeof dest === 'string' || typeof dest === 'number') {\n if (!(this.hasVertex(srcOrEdge) && this.hasVertex(dest))) return false;\n if (srcOrEdge instanceof AbstractVertex) srcOrEdge = srcOrEdge.key;\n if (dest instanceof AbstractVertex) dest = dest.key;\n const newEdge = this.createEdge(srcOrEdge, dest, weight, value);\n return this._addEdge(newEdge);\n } else {\n throw new Error('dest must be a Vertex or vertex key while srcOrEdge is an Edge');\n }\n }\n }\n\n /**\n * Set the weight of an existing edge.\n * @param srcOrKey - Source vertex or key.\n * @param destOrKey - Destination vertex or key.\n * @param weight - New weight.\n * @returns `true` if updated; otherwise `false`.\n * @remarks Time O(1) avg, Space O(1)\n */\n setEdgeWeight(srcOrKey: VertexKey | VO, destOrKey: VertexKey | VO, weight: number): boolean {\n const edge = this.getEdge(srcOrKey, destOrKey);\n if (edge) {\n edge.weight = weight;\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * Enumerate simple paths up to a limit.\n * @param v1 - Source vertex or key.\n * @param v2 - Destination vertex or key.\n * @param limit - Maximum number of paths to collect.\n * @returns Array of paths (each path is an array of vertices).\n * @remarks Time O(paths) worst-case exponential, Space O(V + paths)\n */\n getAllPathsBetween(v1: VO | VertexKey, v2: VO | VertexKey, limit = 1000): VO[][] {\n const paths: VO[][] = [];\n const vertex1 = this._getVertex(v1);\n const vertex2 = this._getVertex(v2);\n\n if (!(vertex1 && vertex2)) {\n return [];\n }\n\n const stack: { vertex: VO; path: VO[] }[] = [];\n stack.push({ vertex: vertex1, path: [vertex1] });\n\n while (stack.length > 0) {\n const { vertex, path } = stack.pop()!;\n\n if (vertex === vertex2) {\n paths.push(path);\n if (paths.length >= limit) return paths;\n }\n\n const neighbors = this.getNeighbors(vertex);\n for (const neighbor of neighbors) {\n if (!path.includes(neighbor)) {\n const newPath = [...path, neighbor];\n stack.push({ vertex: neighbor, path: newPath });\n }\n }\n }\n return paths;\n }\n\n /**\n * Sum the weights along a vertex path.\n * @param path - Sequence of vertices.\n * @returns Path weight sum (0 if empty or edge missing).\n * @remarks Time O(L), Space O(1) where L is path length\n */\n getPathSumWeight(path: VO[]): number {\n let sum = 0;\n for (let i = 0; i < path.length; i++) {\n sum += this.getEdge(path[i], path[i + 1])?.weight || 0;\n }\n return sum;\n }\n\n /**\n * Minimum hops/weight between two vertices.\n * @param v1 - Source vertex or key.\n * @param v2 - Destination vertex or key.\n * @param isWeight - If `true`, compare by path weight; otherwise by hop count.\n * @returns Minimum cost or `undefined` if missing/unreachable.\n * @remarks Time O((V + E) log V) weighted / O(V + E) unweighted, Space O(V + E)\n */\n getMinCostBetween(v1: VO | VertexKey, v2: VO | VertexKey, isWeight?: boolean): number | undefined {\n if (isWeight === undefined) isWeight = false;\n\n if (isWeight) {\n const allPaths = this.getAllPathsBetween(v1, v2);\n let min = Number.MAX_SAFE_INTEGER;\n for (const path of allPaths) {\n min = Math.min(this.getPathSumWeight(path), min);\n }\n return min;\n } else {\n const vertex2 = this._getVertex(v2);\n const vertex1 = this._getVertex(v1);\n if (!(vertex1 && vertex2)) {\n return undefined;\n }\n\n const visited: Map<VO, boolean> = new Map();\n const queue = new Queue<VO>([vertex1]);\n visited.set(vertex1, true);\n let cost = 0;\n while (queue.length > 0) {\n for (let i = 0, layerSize = queue.length; i < layerSize; i++) {\n const cur = queue.shift();\n if (cur === vertex2) {\n return cost;\n }\n\n if (cur !== undefined) {\n const neighbors = this.getNeighbors(cur);\n for (const neighbor of neighbors) {\n if (!visited.has(neighbor)) {\n visited.set(neighbor, true);\n queue.push(neighbor);\n }\n }\n }\n }\n cost++;\n }\n return undefined;\n }\n }\n\n /**\n * Minimum path (as vertex sequence) between two vertices.\n * @param v1 - Source vertex or key.\n * @param v2 - Destination vertex or key.\n * @param isWeight - If `true`, compare by path weight; otherwise by hop count.\n * @param isDFS - For weighted mode only: if `true`, brute-force all paths; if `false`, use Dijkstra.\n * @returns Vertex sequence, or `undefined`/empty when unreachable depending on branch.\n * @remarks Time O((V + E) log V) weighted / O(V + E) unweighted, Space O(V + E)\n */\n getMinPathBetween(v1: VO | VertexKey, v2: VO | VertexKey, isWeight?: boolean, isDFS = false): VO[] | undefined {\n if (isWeight === undefined) isWeight = false;\n\n if (isWeight) {\n if (isDFS) {\n const allPaths = this.getAllPathsBetween(v1, v2, 10000);\n let min = Number.MAX_SAFE_INTEGER;\n let minIndex = -1;\n let index = 0;\n for (const path of allPaths) {\n const pathSumWeight = this.getPathSumWeight(path);\n if (pathSumWeight < min) {\n min = pathSumWeight;\n minIndex = index;\n }\n index++;\n }\n return allPaths[minIndex] || undefined;\n } else {\n /**\n * Dijkstra (binary-heap) shortest paths for non-negative weights.\n * @param src - Source vertex or key.\n * @param dest - Optional destination for early stop.\n * @param getMinDist - If `true`, compute global minimum distance.\n * @param genPaths - If `true`, also generate path arrays.\n * @returns Result bag or `undefined` if source missing.\n * @remarks Time O((V + E) log V), Space O(V + E)\n */\n return this.dijkstra(v1, v2, true, true)?.minPath ?? [];\n }\n } else {\n let minPath: VO[] = [];\n const vertex1 = this._getVertex(v1);\n const vertex2 = this._getVertex(v2);\n if (!(vertex1 && vertex2)) return [];\n\n const dfs = (cur: VO, dest: VO, visiting: Set<VO>, path: VO[]) => {\n visiting.add(cur);\n if (cur === dest) {\n minPath = [vertex1, ...path];\n return;\n }\n\n const neighbors = this.getNeighbors(cur);\n for (const neighbor of neighbors) {\n if (!visiting.has(neighbor)) {\n path.push(neighbor);\n dfs(neighbor, dest, visiting, path);\n path.pop();\n }\n }\n\n visiting.delete(cur);\n };\n\n dfs(vertex1, vertex2, new Set<VO>(), []);\n return minPath;\n }\n }\n\n /**\n * Dijkstra without heap (array-based selection).\n * @param src - Source vertex or key.\n * @param dest - Optional destination for early stop.\n * @param getMinDist - If `true`, compute global minimum distance.\n * @param genPaths - If `true`, also generate path arrays.\n * @returns Result bag or `undefined` if source missing.\n * @remarks Time O(V^2 + E), Space O(V + E)\n */\n dijkstraWithoutHeap(\n src: VO | VertexKey,\n dest: VO | VertexKey | undefined = undefined,\n getMinDist: boolean = false,\n genPaths: boolean = false\n ): DijkstraResult<VO> | undefined {\n let minDist = Number.MAX_SAFE_INTEGER;\n let minDest: VO | undefined = undefined;\n let minPath: VO[] = [];\n const paths: VO[][] = [];\n\n const vertexMap = this._vertexMap;\n const distMap: Map<VO, number> = new Map();\n const seen: Set<VO> = new Set();\n const preMap: Map<VO, VO | undefined> = new Map();\n const srcVertex = this._getVertex(src);\n\n const destVertex = dest ? this._getVertex(dest) : undefined;\n\n if (!srcVertex) {\n return undefined;\n }\n\n for (const vertex of vertexMap) {\n const vertexOrKey = vertex[1];\n if (vertexOrKey instanceof AbstractVertex) distMap.set(vertexOrKey, Number.MAX_SAFE_INTEGER);\n }\n distMap.set(srcVertex, 0);\n preMap.set(srcVertex, undefined);\n\n const getMinOfNoSeen = () => {\n let min = Number.MAX_SAFE_INTEGER;\n let minV: VO | undefined = undefined;\n for (const [key, value] of distMap) {\n if (!seen.has(key)) {\n if (value < min) {\n min = value;\n minV = key;\n }\n }\n }\n return minV;\n };\n\n const getPaths = (minV: VO | undefined) => {\n for (const vertex of vertexMap) {\n const vertexOrKey = vertex[1];\n\n if (vertexOrKey instanceof AbstractVertex) {\n const path: VO[] = [vertexOrKey];\n let parent = preMap.get(vertexOrKey);\n while (parent) {\n path.push(parent);\n parent = preMap.get(parent);\n }\n const reversed = path.reverse();\n if (vertex[1] === minV) minPath = reversed;\n paths.push(reversed);\n }\n }\n };\n\n for (let i = 1; i < vertexMap.size; i++) {\n const cur = getMinOfNoSeen();\n if (cur) {\n seen.add(cur);\n if (destVertex && destVertex === cur) {\n if (getMinDist) {\n minDist = distMap.get(destVertex) || Number.MAX_SAFE_INTEGER;\n }\n if (genPaths) {\n getPaths(destVertex);\n }\n return { distMap, preMap, seen, paths, minDist, minPath };\n }\n const neighbors = this.getNeighbors(cur);\n for (const neighbor of neighbors) {\n if (!seen.has(neighbor)) {\n const edge = this.getEdge(cur, neighbor);\n if (edge) {\n const curFromMap = distMap.get(cur);\n const neighborFromMap = distMap.get(neighbor);\n\n if (curFromMap !== undefined && neighborFromMap !== undefined) {\n if (edge.weight + curFromMap < neighborFromMap) {\n distMap.set(neighbor, edge.weight + curFromMap);\n preMap.set(neighbor, cur);\n }\n }\n }\n }\n }\n }\n }\n\n if (getMinDist)\n distMap.forEach((d, v) => {\n if (v !== srcVertex) {\n if (d < minDist) {\n minDist = d;\n if (genPaths) minDest = v;\n }\n }\n });\n\n if (genPaths) getPaths(minDest);\n\n return { distMap, preMap, seen, paths, minDist, minPath };\n }\n\n dijkstra(\n src: VO | VertexKey,\n dest: VO | VertexKey | undefined = undefined,\n getMinDist: boolean = false,\n genPaths: boolean = false\n ): DijkstraResult<VO> | undefined {\n let minDist = Number.MAX_SAFE_INTEGER;\n let minDest: VO | undefined = undefined;\n let minPath: VO[] = [];\n const paths: VO[][] = [];\n const vertexMap = this._vertexMap;\n const distMap: Map<VO, number> = new Map();\n const seen: Set<VO> = new Set();\n const preMap: Map<VO, VO | undefined> = new Map();\n\n const srcVertex = this._getVertex(src);\n const destVertex = dest ? this._getVertex(dest) : undefined;\n\n if (!srcVertex) return undefined;\n\n for (const vertex of vertexMap) {\n const vertexOrKey = vertex[1];\n if (vertexOrKey instanceof AbstractVertex) distMap.set(vertexOrKey, Number.MAX_SAFE_INTEGER);\n }\n\n const heap = new Heap<{ key: number; value: VO }>([], { comparator: (a, b) => a.key - b.key });\n heap.add({ key: 0, value: srcVertex });\n\n distMap.set(srcVertex, 0);\n preMap.set(srcVertex, undefined);\n\n const getPaths = (minV: VO | undefined) => {\n for (const vertex of vertexMap) {\n const vertexOrKey = vertex[1];\n if (vertexOrKey instanceof AbstractVertex) {\n const path: VO[] = [vertexOrKey];\n let parent = preMap.get(vertexOrKey);\n while (parent) {\n path.push(parent);\n parent = preMap.get(parent);\n }\n const reversed = path.reverse();\n if (vertex[1] === minV) minPath = reversed;\n paths.push(reversed);\n }\n }\n };\n\n while (heap.size > 0) {\n const curHeapNode = heap.poll();\n const dist = curHeapNode?.key;\n const cur = curHeapNode?.value;\n if (dist !== undefined) {\n if (cur) {\n seen.add(cur);\n if (destVertex && destVertex === cur) {\n if (getMinDist) {\n minDist = distMap.get(destVertex) || Number.MAX_SAFE_INTEGER;\n }\n if (genPaths) {\n getPaths(destVertex);\n }\n return { distMap, preMap, seen, paths, minDist, minPath };\n }\n const neighbors = this.getNeighbors(cur);\n for (const neighbor of neighbors) {\n if (!seen.has(neighbor)) {\n const weight = this.getEdge(cur, neighbor)?.weight;\n if (typeof weight === 'number') {\n const distSrcToNeighbor = distMap.get(neighbor);\n if (distSrcToNeighbor !== undefined) {\n if (dist + weight < distSrcToNeighbor) {\n heap.add({ key: dist + weight, value: neighbor });\n preMap.set(neighbor, cur);\n distMap.set(neighbor, dist + weight);\n }\n }\n }\n }\n }\n }\n }\n }\n\n if (getMinDist) {\n distMap.forEach((d, v) => {\n if (v !== srcVertex) {\n if (d < minDist) {\n minDist = d;\n if (genPaths) minDest = v;\n }\n }\n });\n }\n\n if (genPaths) {\n getPaths(minDest);\n }\n\n return { distMap, preMap, seen, paths, minDist, minPath };\n }\n\n /**\n * Bellman-Ford single-source shortest paths with option to scan negative cycles.\n * @param src - Source vertex or key.\n * @param scanNegativeCycle - If `true`, also detect negative cycles.\n * @param getMin - If `true`, compute global minimum distance.\n * @param genPath - If `true`, generate path arrays via predecessor map.\n * @returns Result bag including distances, predecessors, and optional cycle flag.\n * @remarks Time O(V * E), Space O(V + E)\n */\n bellmanFord(src: VO | VertexKey, scanNegativeCycle?: boolean, getMin?: boolean, genPath?: boolean) {\n if (getMin === undefined) getMin = false;\n if (genPath === undefined) genPath = false;\n\n const srcVertex = this._getVertex(src);\n const paths: VO[][] = [];\n const distMap: Map<VO, number> = new Map();\n const preMap: Map<VO, VO> = new Map();\n let min = Number.MAX_SAFE_INTEGER;\n let minPath: VO[] = [];\n\n let hasNegativeCycle: boolean | undefined;\n if (scanNegativeCycle) hasNegativeCycle = false;\n if (!srcVertex) return { hasNegativeCycle, distMap, preMap, paths, min, minPath };\n\n const vertexMap = this._vertexMap;\n const numOfVertices = vertexMap.size;\n const edgeMap = this.edgeSet();\n const numOfEdges = edgeMap.length;\n\n this._vertexMap.forEach(vertex => {\n distMap.set(vertex, Number.MAX_SAFE_INTEGER);\n });\n\n distMap.set(srcVertex, 0);\n\n for (let i = 1; i < numOfVertices; ++i) {\n for (let j = 0; j < numOfEdges; ++j) {\n const ends = this.getEndsOfEdge(edgeMap[j]);\n if (ends) {\n const [s, d] = ends;\n const weight = edgeMap[j].weight;\n const sWeight = distMap.get(s);\n const dWeight = distMap.get(d);\n if (sWeight !== undefined && dWeight !== undefined) {\n if (distMap.get(s) !== Number.MAX_SAFE_INTEGER && sWeight + weight < dWeight) {\n distMap.set(d, sWeight + weight);\n if (genPath) preMap.set(d, s);\n }\n }\n }\n }\n }\n\n let minDest: VO | undefined = undefined;\n if (getMin) {\n distMap.forEach((d, v) => {\n if (v !== srcVertex) {\n if (d < min) {\n min = d;\n if (genPath) minDest = v;\n }\n }\n });\n }\n\n if (genPath) {\n for (const vertex of vertexMap) {\n const vertexOrKey = vertex[1];\n if (vertexOrKey instanceof AbstractVertex) {\n const path: VO[] = [vertexOrKey];\n let parent = preMap.get(vertexOrKey);\n while (parent !== undefined) {\n path.push(parent);\n parent = preMap.get(parent);\n }\n const reversed = path.reverse();\n if (vertex[1] === minDest) minPath = reversed;\n paths.push(reversed);\n }\n }\n }\n\n for (let j = 0; j < numOfEdges; ++j) {\n const ends = this.getEndsOfEdge(edgeMap[j]);\n if (ends) {\n const [s] = ends;\n const weight = edgeMap[j].weight;\n const sWeight = distMap.get(s);\n if (sWeight) {\n if (sWeight !== Number.MAX_SAFE_INTEGER && sWeight + weight < sWeight) hasNegativeCycle = true;\n }\n }\n }\n\n return { hasNegativeCycle, distMap, preMap, paths, min, minPath };\n }\n\n /**\n * Floyd–Warshall all-pairs shortest paths.\n * @returns `{ costs, predecessor }` matrices.\n * @remarks Time O(V^3), Space O(V^2)\n */\n floydWarshall(): { costs: number[][]; predecessor: (VO | undefined)[][] } {\n const idAndVertices = [...this._vertexMap];\n const n = idAndVertices.length;\n\n const costs: number[][] = [];\n const predecessor: (VO | undefined)[][] = [];\n\n for (let i = 0; i < n; i++) {\n costs[i] = [];\n predecessor[i] = [];\n for (let j = 0; j < n; j++) {\n predecessor[i][j] = undefined;\n }\n }\n\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < n; j++) {\n costs[i][j] = this.getEdge(idAndVertices[i][1], idAndVertices[j][1])?.weight || Number.MAX_SAFE_INTEGER;\n }\n }\n\n for (let k = 0; k < n; k++) {\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < n; j++) {\n if (costs[i][j] > costs[i][k] + costs[k][j]) {\n costs[i][j] = costs[i][k] + costs[k][j];\n predecessor[i][j] = idAndVertices[k][1];\n }\n }\n }\n }\n return { costs, predecessor };\n }\n\n /**\n * Enumerate simple cycles (may be expensive).\n * @param isInclude2Cycle - If `true`, include 2-cycles when graph semantics allow.\n * @returns Array of cycles (each as array of vertex keys).\n * @remarks Time exponential in worst-case, Space O(V + E)\n */\n getCycles(isInclude2Cycle: boolean = false): VertexKey[][] {\n const cycles: VertexKey[][] = [];\n const visited: Set<VO> = new Set();\n\n const dfs = (vertex: VO, currentPath: VertexKey[], visited: Set<VO>) => {\n if (visited.has(vertex)) {\n if (\n ((!isInclude2Cycle && currentPath.length > 2) || (isInclude2Cycle && currentPath.length >= 2)) &&\n currentPath[0] === vertex.key\n ) {\n cycles.push([...currentPath]);\n }\n return;\n }\n\n visited.add(vertex);\n currentPath.push(vertex.key);\n\n for (const neighbor of this.getNeighbors(vertex)) {\n if (neighbor) dfs(neighbor, currentPath, visited);\n }\n\n visited.delete(vertex);\n currentPath.pop();\n };\n\n for (const vertex of this.vertexMap.values()) {\n dfs(vertex, [], visited);\n }\n\n const uniqueCycles = new Map<string, VertexKey[]>();\n\n for (const cycle of cycles) {\n const sorted = [...cycle].sort().toString();\n\n if (uniqueCycles.has(sorted)) continue;\n else {\n uniqueCycles.set(sorted, cycle);\n }\n }\n\n /**\n * Map entries to an array via callback.\n * @param callback - `(key, value, index, self) => T`.\n * @param thisArg - Optional `this` for callback.\n * @returns Mapped results.\n * @remarks Time O(V), Space O(V)\n */\n return [...uniqueCycles].map(cycleString => cycleString[1]);\n }\n\n /**\n * Induced-subgraph filter: keep vertices where `predicate(key, value)` is true,\n * and only keep edges whose endpoints both survive.\n * @param predicate - `(key, value, index, self) => boolean`.\n * @param thisArg - Optional `this` for callback.\n * @returns A new graph of the same concrete class (`this` type).\n * @remarks Time O(V + E), Space O(V + E)\n */\n filter(predicate: EntryCallback<VertexKey, V | undefined, boolean>, thisArg?: any): this {\n const filtered: [VertexKey, V | undefined][] = [];\n let index = 0;\n for (const [key, value] of this) {\n if (predicate.call(thisArg, key, value, index, this)) {\n filtered.push([key, value]);\n }\n index++;\n }\n return this._createLike(filtered, this._snapshotOptions());\n }\n\n /**\n * Preserve the old behavior: return filtered entries as an array.\n * @remarks Time O(V), Space O(V)\n */\n filterEntries(\n predicate: EntryCallback<VertexKey, V | undefined, boolean>,\n thisArg?: any\n ): [VertexKey, V | undefined][] {\n const filtered: [VertexKey, V | undefined][] = [];\n let index = 0;\n for (const [key, value] of this) {\n if (predicate.call(thisArg, key, value, index, this)) {\n filtered.push([key, value]);\n }\n index++;\n }\n return filtered;\n }\n\n map<T>(callback: EntryCallback<VertexKey, V | undefined, T>, thisArg?: any): T[] {\n const mapped: T[] = [];\n let index = 0;\n for (const [key, value] of this) {\n mapped.push(callback.call(thisArg, key, value, index, this));\n index++;\n }\n return mapped;\n }\n\n /**\n * Create a deep clone of the graph with the same species.\n * @remarks Time O(V + E), Space O(V + E)\n */\n /**\n * Create a deep clone of the graph with the same species.\n * @returns A new graph of the same concrete class (`this` type).\n * @remarks Time O(V + E), Space O(V + E)\n */\n clone(): this {\n return this._createLike(undefined, this._snapshotOptions());\n }\n\n // ===== Same-species factory & cloning helpers =====\n\n /**\n * Internal iterator over `[key, value]` entries in insertion order.\n * @returns Iterator of `[VertexKey, V | undefined]`.\n * @remarks Time O(V), Space O(1)\n */\n protected *_getIterator(): IterableIterator<[VertexKey, V | undefined]> {\n for (const vertex of this._vertexMap.values()) {\n yield [vertex.key, vertex.value];\n }\n }\n\n /**\n * Capture configuration needed to reproduce the current graph.\n * Currently the graph has no runtime options, so we return an empty object.\n */\n /**\n * Capture configuration needed to reproduce the current graph.\n * @returns Options bag (opaque to callers).\n * @remarks Time O(1), Space O(1)\n */\n protected _snapshotOptions(): Record<string, unknown> {\n return { graph: { ...this._options } };\n }\n\n /**\n * Create an empty graph instance of the same concrete species (Directed/Undirected/etc).\n * @remarks Time O(1), Space O(1)\n */\n /**\n * Create an empty graph instance of the same concrete species.\n * @param _options - Snapshot options from `_snapshotOptions()`.\n * @returns A new empty graph instance of `this` type.\n * @remarks Time O(1), Space O(1)\n */\n protected _createInstance(_options?: Partial<Record<string, unknown>>): this {\n const Ctor: any = (this as any).constructor;\n const instance: this = new Ctor();\n const graph = (_options as any)?.graph as GraphOptions<V> | undefined;\n if (graph) (instance as any)._options = { ...(instance as any)._options, ...graph };\n else (instance as any)._options = { ...(instance as any)._options, ...(this as any)._options };\n return instance;\n }\n\n /**\n * Create a same-species graph populated with the given entries.\n * Also preserves edges between kept vertices from the source graph.\n * @remarks Time O(V + E), Space O(V + E)\n */\n /**\n * Create a same-species graph populated with entries; preserves edges among kept vertices.\n * @param iter - Optional entries to seed the new graph.\n * @param options - Snapshot options.\n * @returns A new graph of `this` type.\n * @remarks Time O(V + E), Space O(V + E)\n */\n protected _createLike(iter?: Iterable<[VertexKey, V | undefined]>, options?: Partial<Record<string, unknown>>): this {\n const g = this._createInstance(options);\n // 1) Add vertices\n if (iter) {\n for (const [k, v] of iter) {\n (g as any).addVertex(k as VertexKey, v as V | undefined);\n }\n } else {\n for (const [k, v] of this) {\n (g as any).addVertex(k as VertexKey, v as V | undefined);\n }\n }\n // 2) Add edges whose endpoints exist in the new graph\n const edges = this.edgeSet();\n for (const e of edges as any[]) {\n const ends = this.getEndsOfEdge(e as any) as unknown as [any, any] | undefined;\n if (!ends) continue;\n const [va, vb] = ends;\n const ka = (va as any).key as VertexKey;\n const kb = (vb as any).key as VertexKey;\n const hasA = (g as any).hasVertex ? (g as any).hasVertex(ka) : false;\n const hasB = (g as any).hasVertex ? (g as any).hasVertex(kb) : false;\n if (hasA && hasB) {\n const w = (e as any).weight;\n const val = (e as any).value;\n const newEdge = (g as any).createEdge(ka, kb, w, val);\n (g as any)._addEdge(newEdge);\n }\n }\n return g;\n }\n\n /**\n * Internal hook to attach an edge into adjacency structures.\n * @param edge - Edge instance.\n * @returns `true` if inserted; otherwise `false`.\n * @remarks Time O(1) avg, Space O(1)\n */\n protected abstract _addEdge(edge: EO): boolean;\n\n /**\n * Insert a pre-built vertex into the graph.\n * @param newVertex - Concrete vertex instance.\n * @returns `true` if inserted; `false` if key already exists.\n * @remarks Time O(1) avg, Space O(1)\n */\n protected _addVertex(newVertex: VO): boolean {\n if (this.hasVertex(newVertex)) {\n return false;\n }\n this._vertexMap.set(newVertex.key, newVertex);\n return true;\n }\n\n /**\n * Resolve a vertex key or instance to the concrete vertex instance.\n * @param vertexOrKey - Vertex key or existing vertex.\n * @returns Vertex instance or `undefined`.\n * @remarks Time O(1), Space O(1)\n */\n protected _getVertex(vertexOrKey: VertexKey | VO): VO | undefined {\n const vertexKey = this._getVertexKey(vertexOrKey);\n return this._vertexMap.get(vertexKey) || undefined;\n }\n\n /**\n * Resolve a vertex key from a key or vertex instance.\n * @param vertexOrKey - Vertex key or existing vertex.\n * @returns The vertex key.\n * @remarks Time O(1), Space O(1)\n */\n protected _getVertexKey(vertexOrKey: VO | VertexKey): VertexKey {\n return vertexOrKey instanceof AbstractVertex ? vertexOrKey.key : vertexOrKey;\n }\n}\n","/**\n * data-structure-typed\n *\n * @author Pablo Zeng\n * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>\n * @license MIT License\n */\n\nimport type { GraphOptions, TopologicalStatus, VertexKey } from '../../types';\nimport { AbstractEdge, AbstractGraph, AbstractVertex } from './abstract-graph';\nimport { IGraph } from '../../interfaces';\nimport { arrayRemove } from '../../utils';\n\nexport class DirectedVertex<V = any> extends AbstractVertex<V> {\n constructor(key: VertexKey, value?: V) {\n super(key, value);\n }\n}\n\nexport class DirectedEdge<E = any> extends AbstractEdge<E> {\n src: VertexKey;\n dest: VertexKey;\n\n constructor(src: VertexKey, dest: VertexKey, weight?: number, value?: E) {\n super(weight, value);\n this.src = src;\n this.dest = dest;\n }\n}\n\n/**\n * Directed graph implementation.\n * @template V - Vertex value type.\n * @template E - Edge value type.\n * @template VO - Concrete vertex class (extends AbstractVertex<V>).\n * @template EO - Concrete edge class (extends AbstractEdge<E>).\n * @remarks Time O(1), Space O(1)\n * @example examples will be generated by unit test\n */\nexport class DirectedGraph<\n V = any,\n E = any,\n VO extends DirectedVertex<V> = DirectedVertex<V>,\n EO extends DirectedEdge<E> = DirectedEdge<E>\n >\n extends AbstractGraph<V, E, VO, EO>\n implements IGraph<V, E, VO, EO>\n{\n /**\n * Construct a directed graph with runtime defaults.\n * @param options - `GraphOptions<V>` (e.g. `vertexValueInitializer`, `defaultEdgeWeight`).\n * @remarks Time O(1), Space O(1)\n */\n constructor(options?: Partial<GraphOptions<V>>) {\n super(options);\n }\n\n protected _outEdgeMap: Map<VO, EO[]> = new Map<VO, EO[]>();\n\n get outEdgeMap(): Map<VO, EO[]> {\n return this._outEdgeMap;\n }\n\n set outEdgeMap(v: Map<VO, EO[]>) {\n this._outEdgeMap = v;\n }\n\n protected _inEdgeMap: Map<VO, EO[]> = new Map<VO, EO[]>();\n\n get inEdgeMap(): Map<VO, EO[]> {\n return this._inEdgeMap;\n }\n\n set inEdgeMap(v: Map<VO, EO[]>) {\n this._inEdgeMap = v;\n }\n\n /**\n * Construct a directed graph from keys with value initializer `v => v`.\n * @template K - Vertex key type.\n * @param keys - Iterable of vertex keys.\n * @returns DirectedGraph with all keys added.\n * @remarks Time O(V), Space O(V)\n */\n static fromKeys<K extends VertexKey>(keys: Iterable<K>): DirectedGraph<K, any, DirectedVertex<K>, DirectedEdge<any>> {\n const g: DirectedGraph<K, any, DirectedVertex<K>, DirectedEdge<any>> = new DirectedGraph<K, any>({\n vertexValueInitializer: (k: VertexKey) => k as K\n });\n for (const k of keys) g.addVertex(k);\n return g;\n }\n\n /**\n * Construct a directed graph from `[key, value]` entries.\n * @template V - Vertex value type.\n * @param entries - Iterable of `[key, value]` pairs.\n * @returns DirectedGraph with all vertices added.\n * @remarks Time O(V), Space O(V)\n */\n static fromEntries<V>(\n entries: Iterable<[VertexKey, V]>\n ): DirectedGraph<V, any, DirectedVertex<V>, DirectedEdge<any>> {\n const g: DirectedGraph<V, any, DirectedVertex<V>, DirectedEdge<any>> = new DirectedGraph<V, any>();\n for (const [k, v] of entries) g.addVertex(k, v);\n return g;\n }\n\n /**\n * Create a directed vertex instance. Does not insert into the graph.\n * @param key - Vertex identifier.\n * @param value - Optional payload.\n * @returns Concrete vertex instance.\n * @remarks Time O(1), Space O(1)\n */\n createVertex(key: VertexKey, value?: VO['value']): VO {\n return new DirectedVertex(key, value) as VO;\n }\n\n /**\n * Create a directed edge instance. Does not insert into the graph.\n * @param src - Source vertex key.\n * @param dest - Destination vertex key.\n * @param weight - Edge weight; defaults to `defaultEdgeWeight`.\n * @param value - Edge payload.\n * @returns Concrete edge instance.\n * @remarks Time O(1), Space O(1)\n */\n createEdge(src: VertexKey, dest: VertexKey, weight?: number, value?: E): EO {\n return new DirectedEdge(src, dest, weight ?? this.options.defaultEdgeWeight ?? 1, value) as EO;\n }\n\n /**\n * Get the unique edge from `src` to `dest`, if present.\n * @param srcOrKey - Source vertex or key.\n * @param destOrKey - Destination vertex or key.\n * @returns Edge instance or `undefined`.\n * @remarks Time O(1) avg, Space O(1)\n */\n getEdge(srcOrKey: VO | VertexKey | undefined, destOrKey: VO | VertexKey | undefined): EO | undefined {\n let edgeMap: EO[] = [];\n\n if (srcOrKey !== undefined && destOrKey !== undefined) {\n const src: VO | undefined = this._getVertex(srcOrKey);\n const dest: VO | undefined = this._getVertex(destOrKey);\n\n if (src && dest) {\n const srcOutEdges = this._outEdgeMap.get(src);\n if (srcOutEdges) {\n edgeMap = srcOutEdges.filter(edge => edge.dest === dest.key);\n }\n }\n }\n\n return edgeMap[0] || undefined;\n }\n\n /**\n * Delete edge `src -> dest` if present.\n * @param srcOrKey - Source vertex or key.\n * @param destOrKey - Destination vertex or key.\n * @returns Removed edge or `undefined`.\n * @remarks Time O(1) avg, Space O(1)\n */\n deleteEdgeSrcToDest(srcOrKey: VO | VertexKey, destOrKey: VO | VertexKey): EO | undefined {\n const src: VO | undefined = this._getVertex(srcOrKey);\n const dest: VO | undefined = this._getVertex(destOrKey);\n let removed: EO | undefined = undefined;\n if (!src || !dest) {\n return undefined;\n }\n\n const srcOutEdges = this._outEdgeMap.get(src);\n if (srcOutEdges) {\n arrayRemove<EO>(srcOutEdges, (edge: EO) => edge.dest === dest.key);\n }\n\n const destInEdges = this._inEdgeMap.get(dest);\n if (destInEdges) {\n removed = arrayRemove<EO>(destInEdges, (edge: EO) => edge.src === src.key)[0] || undefined;\n }\n return removed;\n }\n\n /**\n * Delete an edge by instance or by `(srcKey, destKey)`.\n * @param edgeOrSrcVertexKey - Edge instance or source vertex/key.\n * @param destVertexKey - Optional destination vertex/key when deleting by pair.\n * @returns Removed edge or `undefined`.\n * @remarks Time O(1) avg, Space O(1)\n */\n deleteEdge(edgeOrSrcVertexKey: EO | VertexKey, destVertexKey?: VertexKey): EO | undefined {\n let removed: EO | undefined = undefined;\n let src: VO | undefined, dest: VO | undefined;\n if (this.isVertexKey(edgeOrSrcVertexKey)) {\n if (this.isVertexKey(destVertexKey)) {\n src = this._getVertex(edgeOrSrcVertexKey);\n dest = this._getVertex(destVertexKey);\n } else {\n return;\n }\n } else {\n src = this._getVertex(edgeOrSrcVertexKey.src);\n dest = this._getVertex(edgeOrSrcVertexKey.dest);\n }\n\n if (src && dest) {\n const srcOutEdges = this._outEdgeMap.get(src);\n if (srcOutEdges && srcOutEdges.length > 0) {\n arrayRemove(srcOutEdges, (edge: EO) => edge.src === src!.key && edge.dest === dest?.key);\n }\n\n const destInEdges = this._inEdgeMap.get(dest);\n if (destInEdges && destInEdges.length > 0) {\n removed = arrayRemove(destInEdges, (edge: EO) => edge.src === src!.key && edge.dest === dest!.key)[0];\n }\n }\n\n return removed;\n }\n\n deleteVertex(vertexOrKey: VO | VertexKey): boolean {\n let vertexKey: VertexKey;\n let vertex: VO | undefined;\n if (this.isVertexKey(vertexOrKey)) {\n vertex = this.getVertex(vertexOrKey);\n vertexKey = vertexOrKey;\n } else {\n vertex = vertexOrKey;\n vertexKey = this._getVertexKey(vertexOrKey);\n }\n\n if (vertex) {\n /**\n * One-step neighbors following outgoing edges.\n * @param vertexOrKey - Vertex or key.\n * @returns Array of neighbor vertices.\n * @remarks Time O(deg_out), Space O(deg_out)\n */\n const neighbors = this.getNeighbors(vertex);\n for (const neighbor of neighbors) {\n this.deleteEdgeSrcToDest(vertex, neighbor);\n }\n this._outEdgeMap.delete(vertex);\n this._inEdgeMap.delete(vertex);\n }\n\n return this._vertexMap.delete(vertexKey);\n }\n\n deleteEdgesBetween(v1: VertexKey | VO, v2: VertexKey | VO): EO[] {\n const removed: EO[] = [];\n\n if (v1 && v2) {\n const v1ToV2 = this.deleteEdgeSrcToDest(v1, v2);\n const v2ToV1 = this.deleteEdgeSrcToDest(v2, v1);\n\n if (v1ToV2) removed.push(v1ToV2);\n if (v2ToV1) removed.push(v2ToV1);\n }\n\n return removed;\n }\n\n /**\n * Incoming edges of a vertex.\n * @param vertexOrKey - Vertex or key.\n * @returns Array of incoming edges.\n * @remarks Time O(deg_in), Space O(deg_in)\n */\n incomingEdgesOf(vertexOrKey: VO | VertexKey): EO[] {\n const target = this._getVertex(vertexOrKey);\n if (target) {\n return this.inEdgeMap.get(target) || [];\n }\n return [];\n }\n\n /**\n * Outgoing edges of a vertex.\n * @param vertexOrKey - Vertex or key.\n * @returns Array of outgoing edges.\n * @remarks Time O(deg_out), Space O(deg_out)\n */\n outgoingEdgesOf(vertexOrKey: VO | VertexKey): EO[] {\n const target = this._getVertex(vertexOrKey);\n if (target) {\n return this._outEdgeMap.get(target) || [];\n }\n return [];\n }\n\n /**\n * Degree (in + out) of a vertex.\n * @param vertexOrKey - Vertex or key.\n * @returns Non-negative integer.\n * @remarks Time O(1) avg, Space O(1)\n */\n degreeOf(vertexOrKey: VertexKey | VO): number {\n /**\n * In-degree of a vertex.\n * @param vertexOrKey - Vertex or key.\n * @returns Non-negative integer.\n * @remarks Time O(1) avg, Space O(1)\n */\n /**\n * Out-degree of a vertex.\n * @param vertexOrKey - Vertex or key.\n * @returns Non-negative integer.\n * @remarks Time O(1) avg, Space O(1)\n */\n return this.outDegreeOf(vertexOrKey) + this.inDegreeOf(vertexOrKey);\n }\n\n inDegreeOf(vertexOrKey: VertexKey | VO): number {\n return this.incomingEdgesOf(vertexOrKey).length;\n }\n\n outDegreeOf(vertexOrKey: VertexKey | VO): number {\n return this.outgoingEdgesOf(vertexOrKey).length;\n }\n\n /**\n * All incident edges of a vertex.\n * @param vertexOrKey - Vertex or key.\n * @returns Array of incident edges.\n * @remarks Time O(deg_in + deg_out), Space O(deg_in + deg_out)\n */\n edgesOf(vertexOrKey: VertexKey | VO): EO[] {\n return [...this.outgoingEdgesOf(vertexOrKey), ...this.incomingEdgesOf(vertexOrKey)];\n }\n\n getEdgeSrc(e: EO): VO | undefined {\n return this._getVertex(e.src);\n }\n\n getEdgeDest(e: EO): VO | undefined {\n return this._getVertex(e.dest);\n }\n\n /**\n * Direct children reachable by one outgoing edge.\n * @param vertex - Vertex or key.\n * @returns Array of neighbor vertices.\n * @remarks Time O(deg_out), Space O(deg_out)\n */\n getDestinations(vertex: VO | VertexKey | undefined): VO[] {\n if (vertex === undefined) {\n return [];\n }\n const destinations: VO[] = [];\n const outgoingEdges = this.outgoingEdgesOf(vertex);\n for (const outEdge of outgoingEdges) {\n const child = this.getEdgeDest(outEdge);\n if (child) {\n destinations.push(child);\n }\n }\n return destinations;\n }\n\n /**\n * Topological sort if DAG; returns `undefined` if a cycle exists.\n * @param propertyName - `'key'` to map to keys; `'vertex'` to keep instances.\n * @returns Array of keys/vertices, or `undefined` when cycle is found.\n * @remarks Time O(V + E), Space O(V)\n */\n topologicalSort(propertyName?: 'vertex' | 'key'): Array<VO | VertexKey> | undefined {\n propertyName = propertyName ?? 'key';\n\n const statusMap: Map<VO | VertexKey, TopologicalStatus> = new Map<VO | VertexKey, TopologicalStatus>();\n for (const entry of this.vertexMap) {\n statusMap.set(entry[1], 0);\n }\n\n let sorted: (VO | VertexKey)[] = [];\n let hasCycle = false;\n const dfs = (cur: VO | VertexKey) => {\n statusMap.set(cur, 1);\n const children = this.getDestinations(cur);\n for (const child of children) {\n const childStatus = statusMap.get(child);\n if (childStatus === 0) {\n dfs(child);\n } else if (childStatus === 1) {\n hasCycle = true;\n }\n }\n statusMap.set(cur, 2);\n sorted.push(cur);\n };\n\n for (const entry of this.vertexMap) {\n if (statusMap.get(entry[1]) === 0) {\n dfs(entry[1]);\n }\n }\n\n if (hasCycle) return undefined;\n\n if (propertyName === 'key') sorted = sorted.map(vertex => (vertex instanceof DirectedVertex ? vertex.key : vertex));\n return sorted.reverse();\n }\n\n edgeSet(): EO[] {\n let edgeMap: EO[] = [];\n this._outEdgeMap.forEach(outEdges => {\n edgeMap = [...edgeMap, ...outEdges];\n });\n return edgeMap;\n }\n\n getNeighbors(vertexOrKey: VO | VertexKey): VO[] {\n const neighbors: VO[] = [];\n const vertex = this._getVertex(vertexOrKey);\n if (vertex) {\n const outEdges = this.outgoingEdgesOf(vertex);\n for (const outEdge of outEdges) {\n const neighbor = this._getVertex(outEdge.dest);\n\n if (neighbor) {\n neighbors.push(neighbor);\n }\n }\n }\n return neighbors;\n }\n\n /**\n * Resolve an edge's `[src, dest]` endpoints to vertex instances.\n * @param edge - Edge instance.\n * @returns `[src, dest]` or `undefined` if either endpoint is missing.\n * @remarks Time O(1), Space O(1)\n */\n getEndsOfEdge(edge: EO): [VO, VO] | undefined {\n if (!this.hasEdge(edge.src, edge.dest)) {\n return undefined;\n }\n const v1 = this._getVertex(edge.src);\n const v2 = this._getVertex(edge.dest);\n if (v1 && v2) {\n return [v1, v2];\n } else {\n return undefined;\n }\n }\n\n /**\n * Whether the graph has no vertices and no edges.\n * @remarks Time O(1), Space O(1)\n */\n isEmpty(): boolean {\n return this.vertexMap.size === 0 && this.inEdgeMap.size === 0 && this.outEdgeMap.size === 0;\n }\n\n /**\n * Remove all vertices and edges.\n * @remarks Time O(V + E), Space O(1)\n */\n clear() {\n this._vertexMap = new Map<VertexKey, VO>();\n this._inEdgeMap = new Map<VO, EO[]>();\n this._outEdgeMap = new Map<VO, EO[]>();\n }\n\n /**\n * Deep clone as the same concrete class.\n * @returns A new graph of the same concrete class (`this` type).\n * @remarks Time O(V + E), Space O(V + E)\n */\n override clone(): this {\n return super.clone();\n }\n\n /**\n * Tarjan's algorithm for strongly connected components.\n * @returns `{ dfnMap, lowMap, SCCs }`.\n * @remarks Time O(V + E), Space O(V + E)\n */\n tarjan(): { dfnMap: Map<VO, number>; lowMap: Map<VO, number>; SCCs: Map<number, VO[]> } {\n const dfnMap = new Map<VO, number>();\n const lowMap = new Map<VO, number>();\n const SCCs = new Map<number, VO[]>();\n\n let time = 0;\n\n const stack: VO[] = [];\n const inStack: Set<VO> = new Set();\n\n const dfs = (vertex: VO) => {\n dfnMap.set(vertex, time);\n lowMap.set(vertex, time);\n time++;\n\n stack.push(vertex);\n inStack.add(vertex);\n\n const neighbors = this.getNeighbors(vertex);\n for (const neighbor of neighbors) {\n if (!dfnMap.has(neighbor)) {\n dfs(neighbor);\n lowMap.set(vertex, Math.min(lowMap.get(vertex)!, lowMap.get(neighbor)!));\n } else if (inStack.has(neighbor)) {\n lowMap.set(vertex, Math.min(lowMap.get(vertex)!, dfnMap.get(neighbor)!));\n }\n }\n\n if (dfnMap.get(vertex) === lowMap.get(vertex)) {\n const SCC: VO[] = [];\n let poppedVertex: VO | undefined;\n\n do {\n poppedVertex = stack.pop();\n inStack.delete(poppedVertex!);\n SCC.push(poppedVertex!);\n } while (poppedVertex !== vertex);\n\n SCCs.set(SCCs.size, SCC);\n }\n };\n\n for (const vertex of this.vertexMap.values()) {\n if (!dfnMap.has(vertex)) {\n dfs(vertex);\n }\n }\n\n return { dfnMap, lowMap, SCCs };\n }\n\n /**\n * DFN index map computed by `tarjan()`.\n * @returns Map from vertex to DFN index.\n * @remarks Time O(V), Space O(V)\n */\n getDFNMap(): Map<VO, number> {\n return this.tarjan().dfnMap;\n }\n\n /**\n * LOW link map computed by `tarjan()`.\n * @returns Map from vertex to LOW value.\n * @remarks Time O(V), Space O(V)\n */\n getLowMap(): Map<VO, number> {\n return this.tarjan().lowMap;\n }\n\n /**\n * Strongly connected components computed by `tarjan()`.\n * @returns Map from SCC id to vertices.\n * @remarks Time O(#SCC + V), Space O(V)\n */\n getSCCs(): Map<number, VO[]> {\n return this.tarjan().SCCs;\n }\n\n /**\n * Internal hook to attach a directed edge into adjacency maps.\n * @param edge - Edge instance.\n * @returns `true` if inserted; otherwise `false`.\n * @remarks Time O(1) avg, Space O(1)\n */\n protected _addEdge(edge: EO): boolean {\n if (!(this.hasVertex(edge.src) && this.hasVertex(edge.dest))) {\n return false;\n }\n\n const srcVertex = this._getVertex(edge.src);\n const destVertex = this._getVertex(edge.dest);\n\n if (srcVertex && destVertex) {\n const srcOutEdges = this._outEdgeMap.get(srcVertex);\n if (srcOutEdges) {\n srcOutEdges.push(edge);\n } else {\n this._outEdgeMap.set(srcVertex, [edge]);\n }\n\n const destInEdges = this._inEdgeMap.get(destVertex);\n if (destInEdges) {\n destInEdges.push(edge);\n } else {\n this._inEdgeMap.set(destVertex, [edge]);\n }\n return true;\n } else {\n return false;\n }\n }\n}\n","import { isComparable } from '../utils';\n\nexport enum DFSOperation {\n VISIT = 0,\n PROCESS = 1\n}\n\nexport class Range<K> {\n constructor(\n public low: K,\n public high: K,\n public includeLow: boolean = true,\n public includeHigh: boolean = true\n ) {\n if (!(isComparable(low) && isComparable(high))) throw new RangeError('low or high is not comparable');\n if (low > high) throw new RangeError('low must be less than or equal to high');\n }\n\n // Determine whether a key is within the range\n isInRange(key: K, comparator: (a: K, b: K) => number): boolean {\n const lowCheck = this.includeLow ? comparator(key, this.low) >= 0 : comparator(key, this.low) > 0;\n const highCheck = this.includeHigh ? comparator(key, this.high) <= 0 : comparator(key, this.high) < 0;\n return lowCheck && highCheck;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACeO,MAAM,SAAS,WAAY;AAChC,WAAO,uCAAuC,QAAQ,QAAQ,SAAU,GAAG;AACzE,YAAM,IAAK,KAAK,OAAO,IAAI,KAAM,GAC/B,IAAI,KAAK,MAAM,IAAK,IAAI,IAAO;AACjC,aAAO,EAAE,SAAS,EAAE;AAAA,IACtB,CAAC;AAAA,EACH;AAWO,MAAM,cAAc,SAAa,OAAY,WAAiE;AACnH,QAAI,IAAI,IACN,MAAM,QAAQ,MAAM,SAAS;AAC/B,UAAM,SAAS,CAAC;AAEhB,WAAO,EAAE,IAAI,KAAK;AAChB,YAAM,QAAQ,MAAM,CAAC;AACrB,UAAI,UAAU,OAAO,GAAG,KAAK,GAAG;AAC9B,eAAO,KAAK,KAAK;AACjB,cAAM,UAAU,OAAO,KAAK,OAAO,KAAK,CAAC;AACzC;AAAA,MACF;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AA8FA,WAAS,sBAAsB,OAA8C;AAC3E,UAAM,YAAY,OAAO;AACzB,QAAI,cAAc,SAAU,QAAO;AAEnC,WAAO,cAAc,YAAY,cAAc,YAAY,cAAc;AAAA,E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AM,cAAc,KAAK,WAAW,IAAI,UAAU;AAClD,YAAI,aAAa;AACf,sBAAY,KAAK,IAAI;AAAA,QACvB,OAAO;AACL,eAAK,WAAW,IAAI,YAAY,CAAC,IAAI,CAAC;AAAA,QACxC;AACA,eAAO;AAAA,MACT,OAAO;AACL,eAAO;AAAA,MACT;AAAA,IACF;AAAA,EACF;;;AC3kBO,MAAK,eAAL,kBAAKC,kBAAL;AACL,IAAAA,4BAAA,WAAQ,KAAR;AACA,IAAAA,4BAAA,aAAU,KAAV;AAFU,WAAAA;AAAA,KAAA;AAKL,MAAM,QAAN,MAAe;AAAA,IACpB,YACS,KACA,MACA,aAAsB,MACtB,cAAuB,MAC9B;AAJO;AACA;AACA;AACA;AAEP,UAAI,EAAE,aAAa,GAAG,KAAK,aAAa,IAAI,GAAI,OAAM,IAAI,WAAW,+BAA+B;AACpG,UAAI,MAAM,KAAM,OAAM,IAAI,WAAW,wCAAwC;AAAA,IAC/E;AAAA;AAAA,IAGA,UAAU,KAAQ,YAA6C;AAC7D,YAAM,WAAW,KAAK,aAAa,WAAW,KAAK,KAAK,GAAG,KAAK,IAAI,WAAW,KAAK,KAAK,GAAG,IAAI;AAChG,YAAM,YAAY,KAAK,cAAc,WAAW,KAAK,KAAK,IAAI,KAAK,IAAI,WAAW,KAAK,KAAK,IAAI,IAAI;AACpG,aAAO,YAAY;AAAA,IACrB;AAAA,EACF;","names":["visited","DFSOperation"]}
@@ -0,0 +1,9 @@
1
+ "use strict";var directedGraphTyped=(()=>{var T=Object.defineProperty;var W=Object.getOwnPropertyDescriptor;var Q=Object.getOwnPropertyNames;var X=Object.prototype.hasOwnProperty;var q=(h,o,e)=>o in h?T(h,o,{enumerable:!0,configurable:!0,writable:!0,value:e}):h[o]=e;var J=(h,o)=>{for(var e in o)T(h,e,{get:o[e],enumerable:!0})},Y=(h,o,e,t)=>{if(o&&typeof o=="object"||typeof o=="function")for(let n of Q(o))!X.call(h,n)&&n!==e&&T(h,n,{get:()=>o[n],enumerable:!(t=W(o,n))||t.enumerable});return h};var Z=h=>Y(T({},"__esModule",{value:!0}),h);var b=(h,o,e)=>q(h,typeof o!="symbol"?o+"":o,e);var $={};J($,{AbstractEdge:()=>v,AbstractGraph:()=>C,AbstractVertex:()=>_,DFSOperation:()=>B,DirectedEdge:()=>D,DirectedGraph:()=>z,DirectedVertex:()=>N,Range:()=>G});var j=function(){return"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".replace(/[x]/g,function(h){let o=Math.random()*16|0;return(h=="x"?o:o&3|8).toString(16)})},I=function(h,o){let e=-1,t=h?h.length:0,n=[];for(;++e<t;){let r=h[e];o(r,e,h)&&(n.push(r),Array.prototype.splice.call(h,e--,1),t--)}return n};function H(h){let o=typeof h;return o==="number"?!0:o==="bigint"||o==="string"||o==="boolean"}function P(h){if(typeof h.valueOf=="function"){let o=h.valueOf();if(o!==h){if(H(o))return o;if(typeof o=="object"&&o!==null)return P(o)}}if(typeof h.toString=="function"){let o=h.toString();if(o!=="[object Object]")return o}return null}function U(h,o=!1){if(h==null)return!1;if(H(h))return!0;if(typeof h!="object")return!1;if(h instanceof Date||o)return!0;let e=P(h);return e==null?!1:H(e)}var A=class{*[Symbol.iterator](...o){yield*this._getIterator(...o)}*entries(){for(let o of this)yield o}*keys(){for(let o of this)yield o[0]}*values(){for(let o of this)yield o[1]}every(o,e){let t=0;for(let n of this)if(!o.call(e,n[0],n[1],t++,this))return!1;return!0}some(o,e){let t=0;for(let n of this)if(o.call(e,n[0],n[1],t++,this))return!0;return!1}forEach(o,e){let t=0;for(let n of this){let[r,s]=n;o.call(e,r,s,t++,this)}}find(o,e){let t=0;for(let n of this){let[r,s]=n;if(o.call(e,r,s,t++,this))return n}}has(o){for(let e of this){let[t]=e;if(t===o)return!0}return!1}hasValue(o){for(let[,e]of this)if(e===o)return!0;return!1}get(o){for(let e of this){let[t,n]=e;if(t===o)return n}}reduce(o,e){let t=e,n=0;for(let r of this){let[s,i]=r;t=o(t,i,s,n++,this)}return t}toVisual(){return[...this]}print(){console.log(this.toVisual())}};var w=class{constructor(o){b(this,"_toElementFn");if(o){let{toElementFn:e}=o;if(typeof e=="function")this._toElementFn=e;else if(e)throw new TypeError("toElementFn must be a function type")}}get toElementFn(){return this._toElementFn}*[Symbol.iterator](...o){yield*this._getIterator(...o)}*values(){for(let o of this)yield o}every(o,e){let t=0;for(let n of this)if(e===void 0){if(!o(n,t++,this))return!1}else if(!o.call(e,n,t++,this))return!1;return!0}some(o,e){let t=0;for(let n of this)if(e===void 0){if(o(n,t++,this))return!0}else if(o.call(e,n,t++,this))return!0;return!1}forEach(o,e){let t=0;for(let n of this)e===void 0?o(n,t++,this):o.call(e,n,t++,this)}find(o,e){let t=0;for(let n of this)if(e===void 0){if(o(n,t++,this))return n}else if(o.call(e,n,t++,this))return n}has(o){for(let e of this)if(e===o)return!0;return!1}reduce(o,e){let t=0,n=this[Symbol.iterator](),r;if(arguments.length>=2)r=e;else{let s=n.next();if(s.done)throw new TypeError("Reduce of empty structure with no initial value");r=s.value,t=1}for(let s of n)r=o(r,s,t++,this);return r}toArray(){return[...this]}toVisual(){return[...this]}print(){console.log(this.toVisual())}};var L=class h extends w{constructor(e=[],t){super(t);b(this,"_equals",Object.is);b(this,"_elements",[]);b(this,"_DEFAULT_COMPARATOR",(e,t)=>{if(typeof e=="object"||typeof t=="object")throw TypeError("When comparing object types, define a custom comparator in options.");return e>t?1:e<t?-1:0});b(this,"_comparator",this._DEFAULT_COMPARATOR);if(t){let{comparator:n}=t;n&&(this._comparator=n)}this.addMany(e)}get elements(){return this._elements}get size(){return this.elements.length}get leaf(){var e;return(e=this.elements[this.size-1])!=null?e:void 0}static from(e,t){return new this(e,t)}static heapify(e,t){return new h(e,t)}add(e){return this._elements.push(e),this._bubbleUp(this.elements.length-1)}addMany(e){let t=[];for(let n of e)if(this.toElementFn){let r=this.add(this.toElementFn(n));t.push(r)}else{let r=this.add(n);t.push(r)}return t}poll(){if(this.elements.length===0)return;let e=this.elements[0],t=this.elements.pop();return this.elements.length&&(this.elements[0]=t,this._sinkDown(0,this.elements.length>>1)),e}peek(){return this.elements[0]}isEmpty(){return this.size===0}clear(){this._elements=[]}refill(e){return this._elements=Array.from(e),this.fix()}has(e){for(let t of this.elements)if(this._equals(t,e))return!0;return!1}delete(e){let t=-1;for(let n=0;n<this.elements.length;n++)if(this._equals(this.elements[n],e)){t=n;break}return t<0?!1:(t===0?this.poll():t===this.elements.length-1?this.elements.pop():(this.elements.splice(t,1,this.elements.pop()),this._bubbleUp(t),this._sinkDown(t,this.elements.length>>1)),!0)}deleteBy(e){let t=-1;for(let n=0;n<this.elements.length;n++)if(e(this.elements[n],n,this)){t=n;break}return t<0?!1:(t===0?this.poll():t===this.elements.length-1?this.elements.pop():(this.elements.splice(t,1,this.elements.pop()),this._bubbleUp(t),this._sinkDown(t,this.elements.length>>1)),!0)}setEquality(e){return this._equals=e,this}dfs(e="PRE"){let t=[],n=r=>{let s=2*r+1,i=s+1;r<this.size&&(e==="IN"?(n(s),t.push(this.elements[r]),n(i)):e==="PRE"?(t.push(this.elements[r]),n(s),n(i)):e==="POST"&&(n(s),n(i),t.push(this.elements[r])))};return n(0),t}fix(){let e=[];for(let t=Math.floor(this.size/2)-1;t>=0;t--)e.push(this._sinkDown(t,this.elements.length>>1));return e}sort(){let e=[],t=this._createInstance();for(let n of this.elements)t.add(n);for(;!t.isEmpty();){let n=t.poll();n!==void 0&&e.push(n)}return e}clone(){let e=this._createInstance();for(let t of this.elements)e.add(t);return e}filter(e,t){let n=this._createInstance(),r=0;for(let s of this)(t===void 0?e(s,r++,this):e.call(t,s,r++,this))?n.add(s):r++;return n}map(e,t,n){let{comparator:r,toElementFn:s,...i}=t!=null?t:{};if(!r)throw new TypeError("Heap.map requires options.comparator for EM");let a=this._createLike([],{...i,comparator:r,toElementFn:s}),l=0;for(let f of this){let c=n===void 0?e(f,l++,this):e.call(n,f,l++,this);a.add(c)}return a}mapSame(e,t){let n=this._createInstance(),r=0;for(let s of this){let i=t===void 0?e(s,r++,this):e.call(t,s,r++,this);n.add(i)}return n}get comparator(){return this._comparator}*_getIterator(){for(let e of this.elements)yield e}_bubbleUp(e){let t=this.elements[e];for(;e>0;){let n=e-1>>1,r=this.elements[n];if(this.comparator(r,t)<=0)break;this.elements[e]=r,e=n}return this.elements[e]=t,!0}_sinkDown(e,t){let n=this.elements[e];for(;e<t;){let r=e<<1|1,s=r+1,i=this.elements[r];if(s<this.elements.length&&this.comparator(i,this.elements[s])>0&&(r=s,i=this.elements[s]),this.comparator(i,n)>=0)break;this.elements[e]=i,e=r}return this.elements[e]=n,!0}_createInstance(e){let t=this.constructor;return new t([],{comparator:this.comparator,toElementFn:this.toElementFn,...e!=null?e:{}})}_createLike(e=[],t){let n=this.constructor;return new n(e,t)}_spawnLike(e){return this._createLike([],e)}};var F=class h extends w{constructor(e){super(e);b(this,"_maxLen",-1);if(e){let{maxLen:t}=e;typeof t=="number"&&t>0&&t%1===0&&(this._maxLen=t)}}get maxLen(){return this._maxLen}indexOf(e,t=0){if(this.length===0)return-1;t<0&&(t=this.length+t),t<0&&(t=0);for(let n=t;n<this.length;n++)if(this.at(n)===e)return n;return-1}lastIndexOf(e,t=this.length-1){if(this.length===0)return-1;t>=this.length&&(t=this.length-1),t<0&&(t=this.length+t);for(let n=t;n>=0;n--)if(this.at(n)===e)return n;return-1}findIndex(e,t){for(let n=0;n<this.length;n++){let r=this.at(n);if(r!==void 0&&e.call(t,r,n,this))return n}return-1}concat(...e){let t=this.clone();for(let n of e)n instanceof h?t.pushMany(n):t.push(n);return t}sort(e){let t=this.toArray();t.sort(e),this.clear();for(let n of t)this.push(n);return this}splice(e,t=0,...n){let r=this._createInstance();e=e<0?this.length+e:e,e=Math.max(0,Math.min(e,this.length)),t=Math.max(0,Math.min(t,this.length-e));for(let s=0;s<t;s++){let i=this.deleteAt(e);i!==void 0&&r.push(i)}for(let s=0;s<n.length;s++)this.addAt(e+s,n[s]);return r}join(e=","){return this.toArray().join(e)}toReversedArray(){let e=[];for(let t=this.length-1;t>=0;t--)e.push(this.at(t));return e}reduceRight(e,t){let n=t!=null?t:0;for(let r=this.length-1;r>=0;r--)n=e(n,this.at(r),r,this);return n}slice(e=0,t=this.length){e=e<0?this.length+e:e,t=t<0?this.length+t:t;let n=this._createInstance();for(let r=e;r<t;r++)n.push(this.at(r));return n}fill(e,t=0,n=this.length){if(t=t<0?this.length+t:t,n=n<0?this.length+n:n,t<0&&(t=0),n>this.length&&(n=this.length),t>=n)return this;for(let r=t;r<n;r++)this.setAt(r,e);return this}};var S=class h extends F{constructor(e=[],t){super(t);b(this,"_elements",[]);b(this,"_offset",0);b(this,"_autoCompactRatio",.5);if(t){let{autoCompactRatio:n=.5}=t;this._autoCompactRatio=n}this.pushMany(e)}get elements(){return this._elements}get offset(){return this._offset}get autoCompactRatio(){return this._autoCompactRatio}set autoCompactRatio(e){this._autoCompactRatio=e}get length(){return this.elements.length-this._offset}get first(){return this.length>0?this.elements[this._offset]:void 0}get last(){return this.length>0?this.elements[this.elements.length-1]:void 0}static fromArray(e){return new h(e)}isEmpty(){return this.length===0}push(e){return this.elements.push(e),this._maxLen>0&&this.length>this._maxLen&&this.shift(),!0}pushMany(e){let t=[];for(let n of e)this.toElementFn?t.push(this.push(this.toElementFn(n))):t.push(this.push(n));return t}shift(){if(this.length===0)return;let e=this.first;return this._offset+=1,this.elements.length>0&&this.offset/this.elements.length>this.autoCompactRatio&&this.compact(),e}delete(e){for(let t=this._offset;t<this.elements.length;t++)if(Object.is(this.elements[t],e))return this.elements.splice(t,1),!0;return!1}at(e){if(!(e<0||e>=this.length))return this._elements[this._offset+e]}deleteAt(e){if(e<0||e>=this.length)return;let t=this._offset+e,[n]=this.elements.splice(t,1);return n}addAt(e,t){return e<0||e>this.length?!1:(this._elements.splice(this._offset+e,0,t),!0)}setAt(e,t){return e<0||e>=this.length?!1:(this._elements[this._offset+e]=t,!0)}reverse(){return this._elements=this.elements.slice(this._offset).reverse(),this._offset=0,this}clear(){this._elements=[],this._offset=0}compact(){return this._elements=this.elements.slice(this._offset),this._offset=0,!0}splice(e,t=0,...n){e=Math.max(0,Math.min(e,this.length)),t=Math.max(0,Math.min(t,this.length-e));let r=this._offset+e,s=this._elements.splice(r,t,...n);this.elements.length>0&&this.offset/this.elements.length>this.autoCompactRatio&&this.compact();let i=this._createInstance({toElementFn:this.toElementFn,maxLen:this._maxLen});return i._setAutoCompactRatio(this._autoCompactRatio),i.pushMany(s),i}clone(){let e=this._createInstance({toElementFn:this.toElementFn,maxLen:this._maxLen});e._setAutoCompactRatio(this._autoCompactRatio);for(let t=this._offset;t<this.elements.length;t++)e.push(this.elements[t]);return e}filter(e,t){let n=this._createInstance({toElementFn:this.toElementFn,maxLen:this._maxLen});n._setAutoCompactRatio(this._autoCompactRatio);let r=0;for(let s of this)e.call(t,s,r,this)&&n.push(s),r++;return n}map(e,t,n){var i,a;let r=new this.constructor([],{toElementFn:t==null?void 0:t.toElementFn,maxLen:(i=t==null?void 0:t.maxLen)!=null?i:this._maxLen,autoCompactRatio:(a=t==null?void 0:t.autoCompactRatio)!=null?a:this._autoCompactRatio}),s=0;for(let l of this)r.push(n===void 0?e(l,s++,this):e.call(n,l,s++,this));return r}mapSame(e,t){var i;let n=this.constructor,r=new n([],{toElementFn:this.toElementFn,maxLen:this._maxLen,autoCompactRatio:this._autoCompactRatio});(i=r._setAutoCompactRatio)==null||i.call(r,this._autoCompactRatio);let s=0;for(let a of this){let l=t===void 0?e(a,s++,this):e.call(t,a,s++,this);r.push(l)}return r}_setAutoCompactRatio(e){this._autoCompactRatio=e}*_getIterator(){for(let e=this._offset;e<this.elements.length;e++)yield this.elements[e]}*_getReverseIterator(){for(let e=this.length-1;e>=0;e--){let t=this.at(e);t!==void 0&&(yield t)}}_createInstance(e){let t=this.constructor;return new t([],e)}_createLike(e=[],t){let n=this.constructor;return new n(e,t)}};var _=class{constructor(o,e){b(this,"key");b(this,"value");this.key=o,this.value=e}},v=class{constructor(o,e){b(this,"value");b(this,"weight");b(this,"_hashCode");this.weight=o!==void 0?o:1,this.value=e,this._hashCode=j()}get hashCode(){return this._hashCode}},C=class extends A{constructor(e){super();b(this,"_options",{defaultEdgeWeight:1});b(this,"_vertexMap",new Map);let t=e==null?void 0:e.graph;this._options={defaultEdgeWeight:1,...t!=null?t:{}}}get options(){return this._options}get vertexMap(){return this._vertexMap}set vertexMap(e){this._vertexMap=e}get size(){return this._vertexMap.size}getVertex(e){return this._vertexMap.get(e)||void 0}hasVertex(e){return this._vertexMap.has(this._getVertexKey(e))}addVertex(e,t){if(e instanceof _)return this._addVertex(e);{let n=this.createVertex(e,t);return this._addVertex(n)}}isVertexKey(e){let t=typeof e;return t==="string"||t==="number"}removeManyVertices(e){let t=[];for(let n of e)t.push(this.deleteVertex(n));return t.length>0}hasEdge(e,t){return!!this.getEdge(e,t)}addEdge(e,t,n,r){if(e instanceof v)return this._addEdge(e);if(t instanceof _||typeof t=="string"||typeof t=="number"){if(!(this.hasVertex(e)&&this.hasVertex(t)))return!1;e instanceof _&&(e=e.key),t instanceof _&&(t=t.key);let s=this.createEdge(e,t,n,r);return this._addEdge(s)}else throw new Error("dest must be a Vertex or vertex key while srcOrEdge is an Edge")}setEdgeWeight(e,t,n){let r=this.getEdge(e,t);return r?(r.weight=n,!0):!1}getAllPathsBetween(e,t,n=1e3){let r=[],s=this._getVertex(e),i=this._getVertex(t);if(!(s&&i))return[];let a=[];for(a.push({vertex:s,path:[s]});a.length>0;){let{vertex:l,path:f}=a.pop();if(l===i&&(r.push(f),r.length>=n))return r;let c=this.getNeighbors(l);for(let d of c)if(!f.includes(d)){let g=[...f,d];a.push({vertex:d,path:g})}}return r}getPathSumWeight(e){var n;let t=0;for(let r=0;r<e.length;r++)t+=((n=this.getEdge(e[r],e[r+1]))==null?void 0:n.weight)||0;return t}getMinCostBetween(e,t,n){if(n===void 0&&(n=!1),n){let r=this.getAllPathsBetween(e,t),s=Number.MAX_SAFE_INTEGER;for(let i of r)s=Math.min(this.getPathSumWeight(i),s);return s}else{let r=this._getVertex(t),s=this._getVertex(e);if(!(s&&r))return;let i=new Map,a=new S([s]);i.set(s,!0);let l=0;for(;a.length>0;){for(let f=0,c=a.length;f<c;f++){let d=a.shift();if(d===r)return l;if(d!==void 0){let g=this.getNeighbors(d);for(let x of g)i.has(x)||(i.set(x,!0),a.push(x))}}l++}return}}getMinPathBetween(e,t,n,r=!1){var s,i;if(n===void 0&&(n=!1),n)if(r){let a=this.getAllPathsBetween(e,t,1e4),l=Number.MAX_SAFE_INTEGER,f=-1,c=0;for(let d of a){let g=this.getPathSumWeight(d);g<l&&(l=g,f=c),c++}return a[f]||void 0}else return(i=(s=this.dijkstra(e,t,!0,!0))==null?void 0:s.minPath)!=null?i:[];else{let a=[],l=this._getVertex(e),f=this._getVertex(t);if(!(l&&f))return[];let c=(d,g,x,y)=>{if(x.add(d),d===g){a=[l,...y];return}let R=this.getNeighbors(d);for(let k of R)x.has(k)||(y.push(k),c(k,g,x,y),y.pop());x.delete(d)};return c(l,f,new Set,[]),a}}dijkstraWithoutHeap(e,t=void 0,n=!1,r=!1){let s=Number.MAX_SAFE_INTEGER,i,a=[],l=[],f=this._vertexMap,c=new Map,d=new Set,g=new Map,x=this._getVertex(e),y=t?this._getVertex(t):void 0;if(!x)return;for(let E of f){let u=E[1];u instanceof _&&c.set(u,Number.MAX_SAFE_INTEGER)}c.set(x,0),g.set(x,void 0);let R=()=>{let E=Number.MAX_SAFE_INTEGER,u;for(let[p,m]of c)d.has(p)||m<E&&(E=m,u=p);return u},k=E=>{for(let u of f){let p=u[1];if(p instanceof _){let m=[p],V=g.get(p);for(;V;)m.push(V),V=g.get(V);let O=m.reverse();u[1]===E&&(a=O),l.push(O)}}};for(let E=1;E<f.size;E++){let u=R();if(u){if(d.add(u),y&&y===u)return n&&(s=c.get(y)||Number.MAX_SAFE_INTEGER),r&&k(y),{distMap:c,preMap:g,seen:d,paths:l,minDist:s,minPath:a};let p=this.getNeighbors(u);for(let m of p)if(!d.has(m)){let V=this.getEdge(u,m);if(V){let O=c.get(u),M=c.get(m);O!==void 0&&M!==void 0&&V.weight+O<M&&(c.set(m,V.weight+O),g.set(m,u))}}}}return n&&c.forEach((E,u)=>{u!==x&&E<s&&(s=E,r&&(i=u))}),r&&k(i),{distMap:c,preMap:g,seen:d,paths:l,minDist:s,minPath:a}}dijkstra(e,t=void 0,n=!1,r=!1){var E;let s=Number.MAX_SAFE_INTEGER,i,a=[],l=[],f=this._vertexMap,c=new Map,d=new Set,g=new Map,x=this._getVertex(e),y=t?this._getVertex(t):void 0;if(!x)return;for(let u of f){let p=u[1];p instanceof _&&c.set(p,Number.MAX_SAFE_INTEGER)}let R=new L([],{comparator:(u,p)=>u.key-p.key});R.add({key:0,value:x}),c.set(x,0),g.set(x,void 0);let k=u=>{for(let p of f){let m=p[1];if(m instanceof _){let V=[m],O=g.get(m);for(;O;)V.push(O),O=g.get(O);let M=V.reverse();p[1]===u&&(a=M),l.push(M)}}};for(;R.size>0;){let u=R.poll(),p=u==null?void 0:u.key,m=u==null?void 0:u.value;if(p!==void 0&&m){if(d.add(m),y&&y===m)return n&&(s=c.get(y)||Number.MAX_SAFE_INTEGER),r&&k(y),{distMap:c,preMap:g,seen:d,paths:l,minDist:s,minPath:a};let V=this.getNeighbors(m);for(let O of V)if(!d.has(O)){let M=(E=this.getEdge(m,O))==null?void 0:E.weight;if(typeof M=="number"){let K=c.get(O);K!==void 0&&p+M<K&&(R.add({key:p+M,value:O}),g.set(O,m),c.set(O,p+M))}}}}return n&&c.forEach((u,p)=>{p!==x&&u<s&&(s=u,r&&(i=p))}),r&&k(i),{distMap:c,preMap:g,seen:d,paths:l,minDist:s,minPath:a}}bellmanFord(e,t,n,r){n===void 0&&(n=!1),r===void 0&&(r=!1);let s=this._getVertex(e),i=[],a=new Map,l=new Map,f=Number.MAX_SAFE_INTEGER,c=[],d;if(t&&(d=!1),!s)return{hasNegativeCycle:d,distMap:a,preMap:l,paths:i,min:f,minPath:c};let g=this._vertexMap,x=g.size,y=this.edgeSet(),R=y.length;this._vertexMap.forEach(E=>{a.set(E,Number.MAX_SAFE_INTEGER)}),a.set(s,0);for(let E=1;E<x;++E)for(let u=0;u<R;++u){let p=this.getEndsOfEdge(y[u]);if(p){let[m,V]=p,O=y[u].weight,M=a.get(m),K=a.get(V);M!==void 0&&K!==void 0&&a.get(m)!==Number.MAX_SAFE_INTEGER&&M+O<K&&(a.set(V,M+O),r&&l.set(V,m))}}let k;if(n&&a.forEach((E,u)=>{u!==s&&E<f&&(f=E,r&&(k=u))}),r)for(let E of g){let u=E[1];if(u instanceof _){let p=[u],m=l.get(u);for(;m!==void 0;)p.push(m),m=l.get(m);let V=p.reverse();E[1]===k&&(c=V),i.push(V)}}for(let E=0;E<R;++E){let u=this.getEndsOfEdge(y[E]);if(u){let[p]=u,m=y[E].weight,V=a.get(p);V&&V!==Number.MAX_SAFE_INTEGER&&V+m<V&&(d=!0)}}return{hasNegativeCycle:d,distMap:a,preMap:l,paths:i,min:f,minPath:c}}floydWarshall(){var s;let e=[...this._vertexMap],t=e.length,n=[],r=[];for(let i=0;i<t;i++){n[i]=[],r[i]=[];for(let a=0;a<t;a++)r[i][a]=void 0}for(let i=0;i<t;i++)for(let a=0;a<t;a++)n[i][a]=((s=this.getEdge(e[i][1],e[a][1]))==null?void 0:s.weight)||Number.MAX_SAFE_INTEGER;for(let i=0;i<t;i++)for(let a=0;a<t;a++)for(let l=0;l<t;l++)n[a][l]>n[a][i]+n[i][l]&&(n[a][l]=n[a][i]+n[i][l],r[a][l]=e[i][1]);return{costs:n,predecessor:r}}getCycles(e=!1){let t=[],n=new Set,r=(i,a,l)=>{if(l.has(i)){(!e&&a.length>2||e&&a.length>=2)&&a[0]===i.key&&t.push([...a]);return}l.add(i),a.push(i.key);for(let f of this.getNeighbors(i))f&&r(f,a,l);l.delete(i),a.pop()};for(let i of this.vertexMap.values())r(i,[],n);let s=new Map;for(let i of t){let a=[...i].sort().toString();s.has(a)||s.set(a,i)}return[...s].map(i=>i[1])}filter(e,t){let n=[],r=0;for(let[s,i]of this)e.call(t,s,i,r,this)&&n.push([s,i]),r++;return this._createLike(n,this._snapshotOptions())}filterEntries(e,t){let n=[],r=0;for(let[s,i]of this)e.call(t,s,i,r,this)&&n.push([s,i]),r++;return n}map(e,t){let n=[],r=0;for(let[s,i]of this)n.push(e.call(t,s,i,r,this)),r++;return n}clone(){return this._createLike(void 0,this._snapshotOptions())}*_getIterator(){for(let e of this._vertexMap.values())yield[e.key,e.value]}_snapshotOptions(){return{graph:{...this._options}}}_createInstance(e){let t=this.constructor,n=new t,r=e==null?void 0:e.graph;return r?n._options={...n._options,...r}:n._options={...n._options,...this._options},n}_createLike(e,t){let n=this._createInstance(t);if(e)for(let[s,i]of e)n.addVertex(s,i);else for(let[s,i]of this)n.addVertex(s,i);let r=this.edgeSet();for(let s of r){let i=this.getEndsOfEdge(s);if(!i)continue;let[a,l]=i,f=a.key,c=l.key,d=n.hasVertex?n.hasVertex(f):!1,g=n.hasVertex?n.hasVertex(c):!1;if(d&&g){let x=s.weight,y=s.value,R=n.createEdge(f,c,x,y);n._addEdge(R)}}return n}_addVertex(e){return this.hasVertex(e)?!1:(this._vertexMap.set(e.key,e),!0)}_getVertex(e){let t=this._getVertexKey(e);return this._vertexMap.get(t)||void 0}_getVertexKey(e){return e instanceof _?e.key:e}};var N=class extends _{constructor(o,e){super(o,e)}},D=class extends v{constructor(e,t,n,r){super(n,r);b(this,"src");b(this,"dest");this.src=e,this.dest=t}},z=class h extends C{constructor(e){super(e);b(this,"_outEdgeMap",new Map);b(this,"_inEdgeMap",new Map)}get outEdgeMap(){return this._outEdgeMap}set outEdgeMap(e){this._outEdgeMap=e}get inEdgeMap(){return this._inEdgeMap}set inEdgeMap(e){this._inEdgeMap=e}static fromKeys(e){let t=new h({vertexValueInitializer:n=>n});for(let n of e)t.addVertex(n);return t}static fromEntries(e){let t=new h;for(let[n,r]of e)t.addVertex(n,r);return t}createVertex(e,t){return new N(e,t)}createEdge(e,t,n,r){var s;return new D(e,t,(s=n!=null?n:this.options.defaultEdgeWeight)!=null?s:1,r)}getEdge(e,t){let n=[];if(e!==void 0&&t!==void 0){let r=this._getVertex(e),s=this._getVertex(t);if(r&&s){let i=this._outEdgeMap.get(r);i&&(n=i.filter(a=>a.dest===s.key))}}return n[0]||void 0}deleteEdgeSrcToDest(e,t){let n=this._getVertex(e),r=this._getVertex(t),s;if(!n||!r)return;let i=this._outEdgeMap.get(n);i&&I(i,l=>l.dest===r.key);let a=this._inEdgeMap.get(r);return a&&(s=I(a,l=>l.src===n.key)[0]||void 0),s}deleteEdge(e,t){let n,r,s;if(this.isVertexKey(e))if(this.isVertexKey(t))r=this._getVertex(e),s=this._getVertex(t);else return;else r=this._getVertex(e.src),s=this._getVertex(e.dest);if(r&&s){let i=this._outEdgeMap.get(r);i&&i.length>0&&I(i,l=>l.src===r.key&&l.dest===(s==null?void 0:s.key));let a=this._inEdgeMap.get(s);a&&a.length>0&&(n=I(a,l=>l.src===r.key&&l.dest===s.key)[0])}return n}deleteVertex(e){let t,n;if(this.isVertexKey(e)?(n=this.getVertex(e),t=e):(n=e,t=this._getVertexKey(e)),n){let r=this.getNeighbors(n);for(let s of r)this.deleteEdgeSrcToDest(n,s);this._outEdgeMap.delete(n),this._inEdgeMap.delete(n)}return this._vertexMap.delete(t)}deleteEdgesBetween(e,t){let n=[];if(e&&t){let r=this.deleteEdgeSrcToDest(e,t),s=this.deleteEdgeSrcToDest(t,e);r&&n.push(r),s&&n.push(s)}return n}incomingEdgesOf(e){let t=this._getVertex(e);return t?this.inEdgeMap.get(t)||[]:[]}outgoingEdgesOf(e){let t=this._getVertex(e);return t?this._outEdgeMap.get(t)||[]:[]}degreeOf(e){return this.outDegreeOf(e)+this.inDegreeOf(e)}inDegreeOf(e){return this.incomingEdgesOf(e).length}outDegreeOf(e){return this.outgoingEdgesOf(e).length}edgesOf(e){return[...this.outgoingEdgesOf(e),...this.incomingEdgesOf(e)]}getEdgeSrc(e){return this._getVertex(e.src)}getEdgeDest(e){return this._getVertex(e.dest)}getDestinations(e){if(e===void 0)return[];let t=[],n=this.outgoingEdgesOf(e);for(let r of n){let s=this.getEdgeDest(r);s&&t.push(s)}return t}topologicalSort(e){e=e!=null?e:"key";let t=new Map;for(let i of this.vertexMap)t.set(i[1],0);let n=[],r=!1,s=i=>{t.set(i,1);let a=this.getDestinations(i);for(let l of a){let f=t.get(l);f===0?s(l):f===1&&(r=!0)}t.set(i,2),n.push(i)};for(let i of this.vertexMap)t.get(i[1])===0&&s(i[1]);if(!r)return e==="key"&&(n=n.map(i=>i instanceof N?i.key:i)),n.reverse()}edgeSet(){let e=[];return this._outEdgeMap.forEach(t=>{e=[...e,...t]}),e}getNeighbors(e){let t=[],n=this._getVertex(e);if(n){let r=this.outgoingEdgesOf(n);for(let s of r){let i=this._getVertex(s.dest);i&&t.push(i)}}return t}getEndsOfEdge(e){if(!this.hasEdge(e.src,e.dest))return;let t=this._getVertex(e.src),n=this._getVertex(e.dest);if(t&&n)return[t,n]}isEmpty(){return this.vertexMap.size===0&&this.inEdgeMap.size===0&&this.outEdgeMap.size===0}clear(){this._vertexMap=new Map,this._inEdgeMap=new Map,this._outEdgeMap=new Map}clone(){return super.clone()}tarjan(){let e=new Map,t=new Map,n=new Map,r=0,s=[],i=new Set,a=l=>{e.set(l,r),t.set(l,r),r++,s.push(l),i.add(l);let f=this.getNeighbors(l);for(let c of f)e.has(c)?i.has(c)&&t.set(l,Math.min(t.get(l),e.get(c))):(a(c),t.set(l,Math.min(t.get(l),t.get(c))));if(e.get(l)===t.get(l)){let c=[],d;do d=s.pop(),i.delete(d),c.push(d);while(d!==l);n.set(n.size,c)}};for(let l of this.vertexMap.values())e.has(l)||a(l);return{dfnMap:e,lowMap:t,SCCs:n}}getDFNMap(){return this.tarjan().dfnMap}getLowMap(){return this.tarjan().lowMap}getSCCs(){return this.tarjan().SCCs}_addEdge(e){if(!(this.hasVertex(e.src)&&this.hasVertex(e.dest)))return!1;let t=this._getVertex(e.src),n=this._getVertex(e.dest);if(t&&n){let r=this._outEdgeMap.get(t);r?r.push(e):this._outEdgeMap.set(t,[e]);let s=this._inEdgeMap.get(n);return s?s.push(e):this._inEdgeMap.set(n,[e]),!0}else return!1}};var B=(e=>(e[e.VISIT=0]="VISIT",e[e.PROCESS=1]="PROCESS",e))(B||{}),G=class{constructor(o,e,t=!0,n=!0){this.low=o;this.high=e;this.includeLow=t;this.includeHigh=n;if(!(U(o)&&U(e)))throw new RangeError("low or high is not comparable");if(o>e)throw new RangeError("low must be less than or equal to high")}isInRange(o,e){let t=this.includeLow?e(o,this.low)>=0:e(o,this.low)>0,n=this.includeHigh?e(o,this.high)<=0:e(o,this.high)<0;return t&&n}};return Z($);})();
2
+ /**
3
+ * data-structure-typed
4
+ *
5
+ * @author Pablo Zeng
6
+ * @copyright Copyright (c) 2022 Pablo Zeng <zrwusa@gmail.com>
7
+ * @license MIT License
8
+ */
9
+ //# sourceMappingURL=directed-graph-typed.min.js.map