doubly-linked-list-typed 2.1.1 → 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 +1299 -0
  2. package/dist/cjs/index.cjs.map +1 -0
  3. package/dist/esm/index.mjs +1294 -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 +11 -2
  44. package/dist/{interfaces → types/interfaces}/binary-tree.d.ts +1 -1
  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/doubly-linked-list-typed.js +1302 -0
  87. package/dist/umd/doubly-linked-list-typed.js.map +1 -0
  88. package/dist/umd/doubly-linked-list-typed.min.js +9 -0
  89. package/dist/umd/doubly-linked-list-typed.min.js.map +1 -0
  90. package/package.json +25 -5
  91. package/src/data-structures/binary-tree/avl-tree-counter.ts +4 -4
  92. package/src/data-structures/binary-tree/avl-tree-multi-map.ts +1 -1
  93. package/src/data-structures/binary-tree/avl-tree.ts +2 -2
  94. package/src/data-structures/binary-tree/binary-tree.ts +4 -4
  95. package/src/data-structures/binary-tree/bst.ts +1 -1
  96. package/src/data-structures/binary-tree/red-black-tree.ts +2 -2
  97. package/src/data-structures/binary-tree/tree-counter.ts +4 -4
  98. package/src/data-structures/binary-tree/tree-multi-map.ts +1 -1
  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 +1 -1
  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 -12
  192. package/dist/index.js +0 -28
  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/data-structures/base/iterable-element-base.ts","../../src/data-structures/base/linear-base.ts","../../src/data-structures/linked-list/doubly-linked-list.ts","../../src/utils/utils.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/linked-list/doubly-linked-list';\nexport * from './types/data-structures/linked-list/doubly-linked-list';\nexport * from './types/common';\nexport * from './types/utils';\nexport * from './common';","import type { ElementCallback, IterableElementBaseOptions, ReduceElementCallback } from '../../types';\n\n/**\n * Base class that makes a data structure iterable and provides common\n * element-wise utilities (e.g., map/filter/reduce/find).\n *\n * @template E The public element type yielded by the structure.\n * @template R The underlying \"raw\" element type used internally or by converters.\n *\n * @remarks\n * This class implements the JavaScript iteration protocol (via `Symbol.iterator`)\n * and offers array-like helpers with predictable time/space complexity.\n */\nexport abstract class IterableElementBase<E, R> implements Iterable<E> {\n /**\n * Create a new iterable base.\n *\n * @param options Optional behavior overrides. When provided, a `toElementFn`\n * is used to convert a raw element (`R`) into a public element (`E`).\n *\n * @remarks\n * Time O(1), Space O(1).\n */\n protected constructor(options?: IterableElementBaseOptions<E, R>) {\n if (options) {\n const { toElementFn } = options;\n if (typeof toElementFn === 'function') this._toElementFn = toElementFn;\n else if (toElementFn) throw new TypeError('toElementFn must be a function type');\n }\n }\n\n /**\n * The converter used to transform a raw element (`R`) into a public element (`E`).\n *\n * @remarks\n * Time O(1), Space O(1).\n */\n protected _toElementFn?: (rawElement: R) => E;\n\n /**\n * Exposes the current `toElementFn`, if configured.\n *\n * @returns The converter function or `undefined` when not set.\n * @remarks\n * Time O(1), Space O(1).\n */\n get toElementFn(): ((rawElement: R) => E) | undefined {\n return this._toElementFn;\n }\n\n /**\n * Returns an iterator over the structure's elements.\n *\n * @param args Optional iterator arguments forwarded to the internal iterator.\n * @returns An `IterableIterator<E>` that yields the elements in traversal order.\n *\n * @remarks\n * Producing the iterator is O(1); consuming the entire iterator is Time O(n) with O(1) extra space.\n */\n *[Symbol.iterator](...args: unknown[]): IterableIterator<E> {\n yield* this._getIterator(...args);\n }\n\n /**\n * Returns an iterator over the values (alias of the default iterator).\n *\n * @returns An `IterableIterator<E>` over all elements.\n * @remarks\n * Creating the iterator is O(1); full iteration is Time O(n), Space O(1).\n */\n *values(): IterableIterator<E> {\n for (const item of this) yield item;\n }\n\n /**\n * Tests whether all elements satisfy the predicate.\n *\n * @template TReturn\n * @param predicate Function invoked for each element with signature `(value, index, self)`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns `true` if every element passes; otherwise `false`.\n *\n * @remarks\n * Time O(n) in the worst case; may exit early when the first failure is found. Space O(1).\n */\n every(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): boolean {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n if (!predicate(item, index++, this)) return false;\n } else {\n const fn = predicate as (this: unknown, v: E, i: number, self: this) => boolean;\n if (!fn.call(thisArg, item, index++, this)) return false;\n }\n }\n return true;\n }\n\n /**\n * Tests whether at least one element satisfies the predicate.\n *\n * @param predicate Function invoked for each element with signature `(value, index, self)`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns `true` if any element passes; otherwise `false`.\n *\n * @remarks\n * Time O(n) in the worst case; may exit early on first success. Space O(1).\n */\n some(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): boolean {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n if (predicate(item, index++, this)) return true;\n } else {\n const fn = predicate as (this: unknown, v: E, i: number, self: this) => boolean;\n if (fn.call(thisArg, item, index++, this)) return true;\n }\n }\n return false;\n }\n\n /**\n * Invokes a callback for each element in iteration order.\n *\n * @param callbackfn Function invoked per element with signature `(value, index, self)`.\n * @param thisArg Optional `this` binding for the callback.\n * @returns `void`.\n *\n * @remarks\n * Time O(n), Space O(1).\n */\n forEach(callbackfn: ElementCallback<E, R, void>, thisArg?: unknown): void {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n callbackfn(item, index++, this);\n } else {\n const fn = callbackfn as (this: unknown, v: E, i: number, self: this) => void;\n fn.call(thisArg, item, index++, this);\n }\n }\n }\n\n /**\n * Finds the first element that satisfies the predicate and returns it.\n *\n * @overload\n * Finds the first element of type `S` (a subtype of `E`) that satisfies the predicate and returns it.\n * @template S\n * @param predicate Type-guard predicate: `(value, index, self) => value is S`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns The matched element typed as `S`, or `undefined` if not found.\n *\n * @overload\n * @param predicate Boolean predicate: `(value, index, self) => boolean`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns The first matching element as `E`, or `undefined` if not found.\n *\n * @remarks\n * Time O(n) in the worst case; may exit early on the first match. Space O(1).\n */\n find<S extends E>(predicate: ElementCallback<E, R, S>, thisArg?: unknown): S | undefined;\n find(predicate: ElementCallback<E, R, unknown>, thisArg?: unknown): E | undefined;\n\n // Implementation signature\n find(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): E | undefined {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n if (predicate(item, index++, this)) return item;\n } else {\n const fn = predicate as (this: unknown, v: E, i: number, self: this) => boolean;\n if (fn.call(thisArg, item, index++, this)) return item;\n }\n }\n return;\n }\n\n /**\n * Checks whether a strictly-equal element exists in the structure.\n *\n * @param element The element to test with `===` equality.\n * @returns `true` if an equal element is found; otherwise `false`.\n *\n * @remarks\n * Time O(n) in the worst case. Space O(1).\n */\n has(element: E): boolean {\n for (const ele of this) if (ele === element) return true;\n return false;\n }\n\n reduce(callbackfn: ReduceElementCallback<E, R>): E;\n reduce(callbackfn: ReduceElementCallback<E, R>, initialValue: E): E;\n reduce<U>(callbackfn: ReduceElementCallback<E, R, U>, initialValue: U): U;\n\n /**\n * Reduces all elements to a single accumulated value.\n *\n * @overload\n * @param callbackfn Reducer of signature `(acc, value, index, self) => nextAcc`. The first element is used as the initial accumulator.\n * @returns The final accumulated value typed as `E`.\n *\n * @overload\n * @param callbackfn Reducer of signature `(acc, value, index, self) => nextAcc`.\n * @param initialValue The initial accumulator value of type `E`.\n * @returns The final accumulated value typed as `E`.\n *\n * @overload\n * @template U The accumulator type when it differs from `E`.\n * @param callbackfn Reducer of signature `(acc: U, value, index, self) => U`.\n * @param initialValue The initial accumulator value of type `U`.\n * @returns The final accumulated value typed as `U`.\n *\n * @remarks\n * Time O(n), Space O(1). Throws if called on an empty structure without `initialValue`.\n */\n reduce<U>(callbackfn: ReduceElementCallback<E, R, U>, initialValue?: U): U {\n let index = 0;\n const iter = this[Symbol.iterator]();\n let acc: U;\n\n if (arguments.length >= 2) {\n acc = initialValue as U;\n } else {\n const first = iter.next();\n if (first.done) throw new TypeError('Reduce of empty structure with no initial value');\n acc = first.value as unknown as U;\n index = 1;\n }\n\n for (const value of iter as unknown as Iterable<E>) {\n acc = callbackfn(acc, value, index++, this);\n }\n return acc;\n }\n\n /**\n * Materializes the elements into a new array.\n *\n * @returns A shallow array copy of the iteration order.\n * @remarks\n * Time O(n), Space O(n).\n */\n toArray(): E[] {\n return [...this];\n }\n\n /**\n * Returns a representation of the structure suitable for quick visualization.\n * Defaults to an array of elements; subclasses may override to provide richer visuals.\n *\n * @returns A visual representation (array by default).\n * @remarks\n * Time O(n), Space O(n).\n */\n toVisual(): E[] {\n return [...this];\n }\n\n /**\n * Prints `toVisual()` to the console. Intended for quick debugging.\n *\n * @returns `void`.\n * @remarks\n * Time O(n) due to materialization, Space O(n) for the intermediate representation.\n */\n print(): void {\n console.log(this.toVisual());\n }\n\n /**\n * Indicates whether the structure currently contains no elements.\n *\n * @returns `true` if empty; otherwise `false`.\n * @remarks\n * Expected Time O(1), Space O(1) for most implementations.\n */\n abstract isEmpty(): boolean;\n\n /**\n * Removes all elements from the structure.\n *\n * @returns `void`.\n * @remarks\n * Expected Time O(1) or O(n) depending on the implementation; Space O(1).\n */\n abstract clear(): void;\n\n /**\n * Creates a structural copy with the same element values and configuration.\n *\n * @returns A clone of the current instance (same concrete type).\n * @remarks\n * Expected Time O(n) to copy elements; Space O(n).\n */\n abstract clone(): this;\n\n /**\n * Maps each element to a new element and returns a new iterable structure.\n *\n * @template EM The mapped element type.\n * @template RM The mapped raw element type used internally by the target structure.\n * @param callback Function with signature `(value, index, self) => mapped`.\n * @param options Optional options for the returned structure, including its `toElementFn`.\n * @param thisArg Optional `this` binding for the callback.\n * @returns A new `IterableElementBase<EM, RM>` containing mapped elements.\n *\n * @remarks\n * Time O(n), Space O(n).\n */\n abstract map<EM, RM>(\n callback: ElementCallback<E, R, EM>,\n options?: IterableElementBaseOptions<EM, RM>,\n thisArg?: unknown\n ): IterableElementBase<EM, RM>;\n\n /**\n * Maps each element to the same element type and returns the same concrete structure type.\n *\n * @param callback Function with signature `(value, index, self) => mappedValue`.\n * @param thisArg Optional `this` binding for the callback.\n * @returns A new instance of the same concrete type with mapped elements.\n *\n * @remarks\n * Time O(n), Space O(n).\n */\n abstract mapSame(callback: ElementCallback<E, R, E>, thisArg?: unknown): this;\n\n /**\n * Filters elements using the provided predicate and returns the same concrete structure type.\n *\n * @param predicate Function with signature `(value, index, self) => boolean`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns A new instance of the same concrete type containing only elements that pass the predicate.\n *\n * @remarks\n * Time O(n), Space O(k) where `k` is the number of kept elements.\n */\n abstract filter(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): this;\n\n /**\n * Internal iterator factory used by the default iterator.\n *\n * @param args Optional iterator arguments.\n * @returns An iterator over elements.\n *\n * @remarks\n * Implementations should yield in O(1) per element with O(1) extra space when possible.\n */\n protected abstract _getIterator(...args: unknown[]): IterableIterator<E>;\n}\n","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 { DoublyLinkedListOptions, ElementCallback, LinearBaseOptions } from '../../types';\nimport { LinearLinkedBase, LinkedListNode } from '../base/linear-base';\n\n/**\n * Node of a doubly linked list; stores value and prev/next links.\n * @remarks Time O(1), Space O(1)\n * @template E\n */\nexport class DoublyLinkedListNode<E = any> extends LinkedListNode<E> {\n /**\n * Create a node.\n * @remarks Time O(1), Space O(1)\n * @param value - Element value to store.\n * @returns New node instance.\n */\n\n constructor(value: E) {\n super(value);\n this._value = value;\n this._next = undefined;\n this._prev = undefined;\n }\n\n protected override _next: DoublyLinkedListNode<E> | undefined;\n\n /**\n * Get the next node link.\n * @remarks Time O(1), Space O(1)\n * @returns Next node or undefined.\n */\n\n override get next(): DoublyLinkedListNode<E> | undefined {\n return this._next;\n }\n\n /**\n * Set the next node link.\n * @remarks Time O(1), Space O(1)\n * @param value - Next node or undefined.\n * @returns void\n */\n\n override set next(value: DoublyLinkedListNode<E> | undefined) {\n this._next = value;\n }\n\n protected _prev: DoublyLinkedListNode<E> | undefined;\n\n /**\n * Get the previous node link.\n * @remarks Time O(1), Space O(1)\n * @returns Previous node or undefined.\n */\n\n get prev(): DoublyLinkedListNode<E> | undefined {\n return this._prev;\n }\n\n /**\n * Set the previous node link.\n * @remarks Time O(1), Space O(1)\n * @param value - Previous node or undefined.\n * @returns void\n */\n\n set prev(value: DoublyLinkedListNode<E> | undefined) {\n this._prev = value;\n }\n}\n\n/**\n * Doubly linked list with O(1) push/pop/unshift/shift and linear scans.\n * @remarks Time O(1), Space O(1)\n * @template E\n * @template R\n * 1. Node Structure: Each node contains three parts: a data field, a pointer (or reference) to the previous node, and a pointer to the next node. This structure allows traversal of the linked list in both directions.\n * 2. Bidirectional Traversal: Unlike singly linked lists, doubly linked lists can be easily traversed forwards or backwards. This makes insertions and deletions in the list more flexible and efficient.\n * 3. No Centralized Index: Unlike arrays, elements in a linked list are not stored contiguously, so there is no centralized index. Accessing elements in a linked list typically requires traversing from the head or tail node.\n * 4. High Efficiency in Insertion and Deletion: Adding or removing elements in a linked list does not require moving other elements, making these operations more efficient than in arrays.\n * Caution: Although our linked list classes provide methods such as at, setAt, addAt, and indexOf that are based on array indices, their time complexity, like that of the native Array.lastIndexOf, is 𝑂(𝑛). If you need to use these methods frequently, you might want to consider other data structures, such as Deque or Queue (designed for random access). Similarly, since the native Array.shift method has a time complexity of 𝑂(𝑛), using an array to simulate a queue can be inefficient. In such cases, you should use Queue or Deque, as these data structures leverage deferred array rearrangement, effectively reducing the average time complexity to 𝑂(1).\n * @example\n * // text editor operation history\n * const actions = [\n * { type: 'insert', content: 'first line of text' },\n * { type: 'insert', content: 'second line of text' },\n * { type: 'delete', content: 'delete the first line' }\n * ];\n * const editorHistory = new DoublyLinkedList<{ type: string; content: string }>(actions);\n *\n * console.log(editorHistory.last?.type); // 'delete'\n * console.log(editorHistory.pop()?.content); // 'delete the first line'\n * console.log(editorHistory.last?.type); // 'insert'\n * @example\n * // Browser history\n * const browserHistory = new DoublyLinkedList<string>();\n *\n * browserHistory.push('home page');\n * browserHistory.push('search page');\n * browserHistory.push('details page');\n *\n * console.log(browserHistory.last); // 'details page'\n * console.log(browserHistory.pop()); // 'details page'\n * console.log(browserHistory.last); // 'search page'\n * @example\n * // Use DoublyLinkedList to implement music player\n * // Define the Song interface\n * interface Song {\n * title: string;\n * artist: string;\n * duration: number; // duration in seconds\n * }\n *\n * class Player {\n * private playlist: DoublyLinkedList<Song>;\n * private currentSong: ReturnType<typeof this.playlist.getNodeAt> | undefined;\n *\n * constructor(songs: Song[]) {\n * this.playlist = new DoublyLinkedList<Song>();\n * songs.forEach(song => this.playlist.push(song));\n * this.currentSong = this.playlist.head;\n * }\n *\n * // Play the next song in the playlist\n * playNext(): Song | undefined {\n * if (!this.currentSong?.next) {\n * this.currentSong = this.playlist.head; // Loop to the first song\n * } else {\n * this.currentSong = this.currentSong.next;\n * }\n * return this.currentSong?.value;\n * }\n *\n * // Play the previous song in the playlist\n * playPrevious(): Song | undefined {\n * if (!this.currentSong?.prev) {\n * this.currentSong = this.playlist.tail; // Loop to the last song\n * } else {\n * this.currentSong = this.currentSong.prev;\n * }\n * return this.currentSong?.value;\n * }\n *\n * // Get the current song\n * getCurrentSong(): Song | undefined {\n * return this.currentSong?.value;\n * }\n *\n * // Loop through the playlist twice\n * loopThroughPlaylist(): Song[] {\n * const playedSongs: Song[] = [];\n * const initialNode = this.currentSong;\n *\n * // Loop through the playlist twice\n * for (let i = 0; i < this.playlist.length * 2; i++) {\n * playedSongs.push(this.currentSong!.value);\n * this.currentSong = this.currentSong!.next || this.playlist.head; // Loop back to the start if needed\n * }\n *\n * // Reset the current song to the initial song\n * this.currentSong = initialNode;\n * return playedSongs;\n * }\n * }\n *\n * const songs = [\n * { title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 },\n * { title: 'Hotel California', artist: 'Eagles', duration: 391 },\n * { title: 'Shape of You', artist: 'Ed Sheeran', duration: 233 },\n * { title: 'Billie Jean', artist: 'Michael Jackson', duration: 294 }\n * ];\n * let player = new Player(songs);\n * // should play the next song\n * player = new Player(songs);\n * const firstSong = player.getCurrentSong();\n * const nextSong = player.playNext();\n *\n * // Expect the next song to be \"Hotel California by Eagles\"\n * console.log(nextSong); // { title: 'Hotel California', artist: 'Eagles', duration: 391 }\n * console.log(firstSong); // { title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 }\n *\n * // should play the previous song\n * player = new Player(songs);\n * player.playNext(); // Move to the second song\n * const currentSong = player.getCurrentSong();\n * const previousSong = player.playPrevious();\n *\n * // Expect the previous song to be \"Bohemian Rhapsody by Queen\"\n * console.log(previousSong); // { title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 }\n * console.log(currentSong); // { title: 'Hotel California', artist: 'Eagles', duration: 391 }\n *\n * // should loop to the first song when playing next from the last song\n * player = new Player(songs);\n * player.playNext(); // Move to the second song\n * player.playNext(); // Move to the third song\n * player.playNext(); // Move to the fourth song\n *\n * const nextSongToFirst = player.playNext(); // Should loop to the first song\n *\n * // Expect the next song to be \"Bohemian Rhapsody by Queen\"\n * console.log(nextSongToFirst); // { title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 }\n *\n * // should loop to the last song when playing previous from the first song\n * player = new Player(songs);\n * player.playNext(); // Move to the first song\n * player.playNext(); // Move to the second song\n * player.playNext(); // Move to the third song\n * player.playNext(); // Move to the fourth song\n *\n * const previousToLast = player.playPrevious(); // Should loop to the last song\n *\n * // Expect the previous song to be \"Billie Jean by Michael Jackson\"\n * console.log(previousToLast); // { title: 'Billie Jean', artist: 'Michael Jackson', duration: 294 }\n *\n * // should loop through the entire playlist\n * player = new Player(songs);\n * const playedSongs = player.loopThroughPlaylist();\n *\n * // The expected order of songs for two loops\n * console.log(playedSongs); // [\n * // { title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 },\n * // { title: 'Hotel California', artist: 'Eagles', duration: 391 },\n * // { title: 'Shape of You', artist: 'Ed Sheeran', duration: 233 },\n * // { title: 'Billie Jean', artist: 'Michael Jackson', duration: 294 },\n * // { title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 },\n * // { title: 'Hotel California', artist: 'Eagles', duration: 391 },\n * // { title: 'Shape of You', artist: 'Ed Sheeran', duration: 233 },\n * // { title: 'Billie Jean', artist: 'Michael Jackson', duration: 294 }\n * // ]\n * @example\n * // Use DoublyLinkedList to implement LRU cache\n * interface CacheEntry<K, V> {\n * key: K;\n * value: V;\n * }\n *\n * class LRUCache<K = string, V = any> {\n * private readonly capacity: number;\n * private list: DoublyLinkedList<CacheEntry<K, V>>;\n * private map: Map<K, DoublyLinkedListNode<CacheEntry<K, V>>>;\n *\n * constructor(capacity: number) {\n * if (capacity <= 0) {\n * throw new Error('lru cache capacity must be greater than 0');\n * }\n * this.capacity = capacity;\n * this.list = new DoublyLinkedList<CacheEntry<K, V>>();\n * this.map = new Map<K, DoublyLinkedListNode<CacheEntry<K, V>>>();\n * }\n *\n * // Get the current cache length\n * get length(): number {\n * return this.list.length;\n * }\n *\n * // Check if it is empty\n * get isEmpty(): boolean {\n * return this.list.isEmpty();\n * }\n *\n * // Get cached value\n * get(key: K): V | undefined {\n * const node = this.map.get(key);\n *\n * if (!node) return undefined;\n *\n * // Move the visited node to the head of the linked list (most recently used)\n * this.moveToFront(node);\n *\n * return node.value.value;\n * }\n *\n * // Set cache value\n * set(key: K, value: V): void {\n * // Check if it already exists\n * const node = this.map.get(key);\n *\n * if (node) {\n * // Update value and move to head\n * node.value.value = value;\n * this.moveToFront(node);\n * return;\n * }\n *\n * // Check capacity\n * if (this.list.length >= this.capacity) {\n * // Delete the least recently used element (the tail of the linked list)\n * const removedNode = this.list.tail;\n * if (removedNode) {\n * this.map.delete(removedNode.value.key);\n * this.list.pop();\n * }\n * }\n *\n * // Create new node and add to head\n * const newEntry: CacheEntry<K, V> = { key, value };\n * this.list.unshift(newEntry);\n *\n * // Save node reference in map\n * const newNode = this.list.head;\n * if (newNode) {\n * this.map.set(key, newNode);\n * }\n * }\n *\n * // Delete specific key\n * delete(key: K): boolean {\n * const node = this.map.get(key);\n * if (!node) return false;\n *\n * // Remove from linked list\n * this.list.delete(node);\n * // Remove from map\n * this.map.delete(key);\n *\n * return true;\n * }\n *\n * // Clear cache\n * clear(): void {\n * this.list.clear();\n * this.map.clear();\n * }\n *\n * // Move the node to the head of the linked list\n * private moveToFront(node: DoublyLinkedListNode<CacheEntry<K, V>>): void {\n * this.list.delete(node);\n * this.list.unshift(node.value);\n * }\n * }\n *\n * // should set and get values correctly\n * const cache = new LRUCache<string, number>(3);\n * cache.set('a', 1);\n * cache.set('b', 2);\n * cache.set('c', 3);\n *\n * console.log(cache.get('a')); // 1\n * console.log(cache.get('b')); // 2\n * console.log(cache.get('c')); // 3\n *\n * // The least recently used element should be evicted when capacity is exceeded\n * cache.clear();\n * cache.set('a', 1);\n * cache.set('b', 2);\n * cache.set('c', 3);\n * cache.set('d', 4); // This will eliminate 'a'\n *\n * console.log(cache.get('a')); // undefined\n * console.log(cache.get('b')); // 2\n * console.log(cache.get('c')); // 3\n * console.log(cache.get('d')); // 4\n *\n * // The priority of an element should be updated when it is accessed\n * cache.clear();\n * cache.set('a', 1);\n * cache.set('b', 2);\n * cache.set('c', 3);\n *\n * cache.get('a'); // access 'a'\n * cache.set('d', 4); // This will eliminate 'b'\n *\n * console.log(cache.get('a')); // 1\n * console.log(cache.get('b')); // undefined\n * console.log(cache.get('c')); // 3\n * console.log(cache.get('d')); // 4\n *\n * // Should support updating existing keys\n * cache.clear();\n * cache.set('a', 1);\n * cache.set('a', 10);\n *\n * console.log(cache.get('a')); // 10\n *\n * // Should support deleting specified keys\n * cache.clear();\n * cache.set('a', 1);\n * cache.set('b', 2);\n *\n * console.log(cache.delete('a')); // true\n * console.log(cache.get('a')); // undefined\n * console.log(cache.length); // 1\n *\n * // Should support clearing cache\n * cache.clear();\n * cache.set('a', 1);\n * cache.set('b', 2);\n * cache.clear();\n *\n * console.log(cache.length); // 0\n * console.log(cache.isEmpty); // true\n * @example\n * // finding lyrics by timestamp in Coldplay's \"Fix You\"\n * // Create a DoublyLinkedList to store song lyrics with timestamps\n * const lyricsList = new DoublyLinkedList<{ time: number; text: string }>();\n *\n * // Detailed lyrics with precise timestamps (in milliseconds)\n * const lyrics = [\n * { time: 0, text: \"When you try your best, but you don't succeed\" },\n * { time: 4000, text: 'When you get what you want, but not what you need' },\n * { time: 8000, text: \"When you feel so tired, but you can't sleep\" },\n * { time: 12000, text: 'Stuck in reverse' },\n * { time: 16000, text: 'And the tears come streaming down your face' },\n * { time: 20000, text: \"When you lose something you can't replace\" },\n * { time: 24000, text: 'When you love someone, but it goes to waste' },\n * { time: 28000, text: 'Could it be worse?' },\n * { time: 32000, text: 'Lights will guide you home' },\n * { time: 36000, text: 'And ignite your bones' },\n * { time: 40000, text: 'And I will try to fix you' }\n * ];\n *\n * // Populate the DoublyLinkedList with lyrics\n * lyrics.forEach(lyric => lyricsList.push(lyric));\n *\n * // Test different scenarios of lyric synchronization\n *\n * // 1. Find lyric at exact timestamp\n * const exactTimeLyric = lyricsList.getBackward(lyric => lyric.value.time <= 36000);\n * console.log(exactTimeLyric?.text); // 'And ignite your bones'\n *\n * // 2. Find lyric between timestamps\n * const betweenTimeLyric = lyricsList.getBackward(lyric => lyric.value.time <= 22000);\n * console.log(betweenTimeLyric?.text); // \"When you lose something you can't replace\"\n *\n * // 3. Find first lyric when timestamp is less than first entry\n * const earlyTimeLyric = lyricsList.getBackward(lyric => lyric.value.time <= -1000);\n * console.log(earlyTimeLyric); // undefined\n *\n * // 4. Find last lyric when timestamp is after last entry\n * const lateTimeLyric = lyricsList.getBackward(lyric => lyric.value.time <= 50000);\n * console.log(lateTimeLyric?.text); // 'And I will try to fix you'\n * @example\n * // cpu process schedules\n * class Process {\n * constructor(\n * public id: number,\n * public priority: number\n * ) {}\n *\n * execute(): string {\n * return `Process ${this.id} executed.`;\n * }\n * }\n *\n * class Scheduler {\n * private queue: DoublyLinkedList<Process>;\n *\n * constructor() {\n * this.queue = new DoublyLinkedList<Process>();\n * }\n *\n * addProcess(process: Process): void {\n * // Insert processes into a queue based on priority, keeping priority in descending order\n * let current = this.queue.head;\n * while (current && current.value.priority >= process.priority) {\n * current = current.next;\n * }\n *\n * if (!current) {\n * this.queue.push(process);\n * } else {\n * this.queue.addBefore(current, process);\n * }\n * }\n *\n * executeNext(): string | undefined {\n * // Execute tasks at the head of the queue in order\n * const process = this.queue.shift();\n * return process ? process.execute() : undefined;\n * }\n *\n * listProcesses(): string[] {\n * return this.queue.toArray().map(process => `Process ${process.id} (Priority: ${process.priority})`);\n * }\n *\n * clear(): void {\n * this.queue.clear();\n * }\n * }\n *\n * // should add processes based on priority\n * let scheduler = new Scheduler();\n * scheduler.addProcess(new Process(1, 10));\n * scheduler.addProcess(new Process(2, 20));\n * scheduler.addProcess(new Process(3, 15));\n *\n * console.log(scheduler.listProcesses()); // [\n * // 'Process 2 (Priority: 20)',\n * // 'Process 3 (Priority: 15)',\n * // 'Process 1 (Priority: 10)'\n * // ]\n *\n * // should execute the highest priority process\n * scheduler = new Scheduler();\n * scheduler.addProcess(new Process(1, 10));\n * scheduler.addProcess(new Process(2, 20));\n *\n * console.log(scheduler.executeNext()); // 'Process 2 executed.'\n * console.log(scheduler.listProcesses()); // ['Process 1 (Priority: 10)']\n *\n * // should clear all processes\n * scheduler = new Scheduler();\n * scheduler.addProcess(new Process(1, 10));\n * scheduler.addProcess(new Process(2, 20));\n *\n * scheduler.clear();\n * console.log(scheduler.listProcesses()); // []\n */\nexport class DoublyLinkedList<E = any, R = any> extends LinearLinkedBase<E, R, DoublyLinkedListNode<E>> {\n protected _equals: (a: E, b: E) => boolean = Object.is as unknown as (a: E, b: E) => boolean;\n\n /**\n * Create a DoublyLinkedList and optionally bulk-insert elements.\n * @remarks Time O(N), Space O(N)\n * @param [elements] - Iterable of elements or nodes (or raw records if toElementFn is provided).\n * @param [options] - Options such as maxLen and toElementFn.\n * @returns New DoublyLinkedList instance.\n */\n\n constructor(\n elements: Iterable<E> | Iterable<R> | Iterable<DoublyLinkedListNode<E>> = [],\n options?: DoublyLinkedListOptions<E, R>\n ) {\n super(options);\n this._head = undefined;\n this._tail = undefined;\n this._length = 0;\n\n if (options?.maxLen && Number.isInteger(options.maxLen) && options.maxLen > 0) {\n this._maxLen = options.maxLen;\n }\n\n this.pushMany(elements);\n }\n\n protected _head: DoublyLinkedListNode<E> | undefined;\n\n /**\n * Get the head node.\n * @remarks Time O(1), Space O(1)\n * @returns Head node or undefined.\n */\n\n get head(): DoublyLinkedListNode<E> | undefined {\n return this._head;\n }\n\n protected _tail: DoublyLinkedListNode<E> | undefined;\n\n /**\n * Get the tail node.\n * @remarks Time O(1), Space O(1)\n * @returns Tail node or undefined.\n */\n\n get tail(): DoublyLinkedListNode<E> | undefined {\n return this._tail;\n }\n\n protected _length = 0;\n\n /**\n * Get the number of elements.\n * @remarks Time O(1), Space O(1)\n * @returns Current length.\n */\n\n get length(): number {\n return this._length;\n }\n\n /**\n * Get the first element value.\n * @remarks Time O(1), Space O(1)\n * @returns First element or undefined.\n */\n\n get first(): E | undefined {\n return this.head?.value;\n }\n\n /**\n * Get the last element value.\n * @remarks Time O(1), Space O(1)\n * @returns Last element or undefined.\n */\n\n get last(): E | undefined {\n return this.tail?.value;\n }\n\n /**\n * Create a new list from an array of elements.\n * @remarks Time O(N), Space O(N)\n * @template E\n * @template R\n * @param this - The constructor (subclass) to instantiate.\n * @param data - Array of elements to insert.\n * @returns A new list populated with the array's elements.\n */\n\n static fromArray<E, R = any>(\n this: new (\n elements?: Iterable<E> | Iterable<R> | Iterable<DoublyLinkedListNode<E>>,\n options?: DoublyLinkedListOptions<E, R>\n ) => any,\n data: E[]\n ) {\n return new this(data);\n }\n\n /**\n * Type guard: check whether the input is a DoublyLinkedListNode.\n * @remarks Time O(1), Space O(1)\n * @param elementNodeOrPredicate - Element, node, or predicate.\n * @returns True if the value is a DoublyLinkedListNode.\n */\n\n isNode(\n elementNodeOrPredicate: E | DoublyLinkedListNode<E> | ((node: DoublyLinkedListNode<E>) => boolean)\n ): elementNodeOrPredicate is DoublyLinkedListNode<E> {\n return elementNodeOrPredicate instanceof DoublyLinkedListNode;\n }\n\n /**\n * Append an element/node to the tail.\n * @remarks Time O(1), Space O(1)\n * @param elementOrNode - Element or node to append.\n * @returns True when appended.\n */\n\n push(elementOrNode: E | DoublyLinkedListNode<E>): boolean {\n const newNode = this._ensureNode(elementOrNode);\n if (!this.head) {\n this._head = newNode;\n this._tail = newNode;\n } else {\n newNode.prev = this.tail;\n this.tail!.next = newNode;\n this._tail = newNode;\n }\n this._length++;\n if (this._maxLen > 0 && this.length > this._maxLen) this.shift();\n return true;\n }\n\n /**\n * Remove and return the tail element.\n * @remarks Time O(1), Space O(1)\n * @returns Removed element or undefined.\n */\n\n pop(): E | undefined {\n if (!this.tail) return undefined;\n const removed = this.tail;\n if (this.head === this.tail) {\n this._head = undefined;\n this._tail = undefined;\n } else {\n this._tail = removed.prev;\n this.tail!.next = undefined;\n }\n this._length--;\n return removed.value;\n }\n\n /**\n * Remove and return the head element.\n * @remarks Time O(1), Space O(1)\n * @returns Removed element or undefined.\n */\n\n shift(): E | undefined {\n if (!this.head) return undefined;\n const removed = this.head;\n if (this.head === this.tail) {\n this._head = undefined;\n this._tail = undefined;\n } else {\n this._head = removed.next;\n this.head!.prev = undefined;\n }\n this._length--;\n return removed.value;\n }\n\n /**\n * Prepend an element/node to the head.\n * @remarks Time O(1), Space O(1)\n * @param elementOrNode - Element or node to prepend.\n * @returns True when prepended.\n */\n\n unshift(elementOrNode: E | DoublyLinkedListNode<E>): boolean {\n const newNode = this._ensureNode(elementOrNode);\n if (!this.head) {\n this._head = newNode;\n this._tail = newNode;\n } else {\n newNode.next = this.head;\n this.head!.prev = newNode;\n this._head = newNode;\n }\n this._length++;\n if (this._maxLen > 0 && this._length > this._maxLen) this.pop();\n return true;\n }\n\n /**\n * Append a sequence of elements/nodes.\n * @remarks Time O(N), Space O(1)\n * @param elements - Iterable of elements or nodes (or raw records if toElementFn is provided).\n * @returns Array of per-element success flags.\n */\n\n pushMany(elements: Iterable<E> | Iterable<R> | Iterable<DoublyLinkedListNode<E>>): 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 | DoublyLinkedListNode<E>));\n }\n return ans;\n }\n\n /**\n * Prepend a sequence of elements/nodes.\n * @remarks Time O(N), Space O(1)\n * @param elements - Iterable of elements or nodes (or raw records if toElementFn is provided).\n * @returns Array of per-element success flags.\n */\n\n unshiftMany(elements: Iterable<E> | Iterable<R> | Iterable<DoublyLinkedListNode<E>>): boolean[] {\n const ans: boolean[] = [];\n for (const el of elements) {\n if (this.toElementFn) ans.push(this.unshift(this.toElementFn(el as R)));\n else ans.push(this.unshift(el as E | DoublyLinkedListNode<E>));\n }\n return ans;\n }\n\n /**\n * Get the element at a given index.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index.\n * @returns Element or undefined.\n */\n\n at(index: number): E | undefined {\n if (index < 0 || index >= this._length) return undefined;\n let current = this.head;\n for (let i = 0; i < index; i++) current = current!.next;\n return current!.value;\n }\n\n /**\n * Get the node reference at a given index.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index.\n * @returns Node or undefined.\n */\n\n getNodeAt(index: number): DoublyLinkedListNode<E> | undefined {\n if (index < 0 || index >= this._length) return undefined;\n let current = this.head;\n for (let i = 0; i < index; i++) current = current!.next;\n return current;\n }\n\n /**\n * Find a node by value, reference, or predicate.\n * @remarks Time O(N), Space O(1)\n * @param [elementNodeOrPredicate] - Element, node, or predicate to match.\n * @returns Matching node or undefined.\n */\n\n getNode(\n elementNodeOrPredicate: E | DoublyLinkedListNode<E> | ((node: DoublyLinkedListNode<E>) => boolean) | undefined\n ): DoublyLinkedListNode<E> | undefined {\n if (elementNodeOrPredicate === undefined) return;\n\n if (this.isNode(elementNodeOrPredicate)) {\n const target = elementNodeOrPredicate;\n\n let cur = this.head;\n while (cur) {\n if (cur === target) return target;\n cur = cur.next;\n }\n\n const isMatch = (node: DoublyLinkedListNode<E>) => this._equals(node.value, target.value);\n cur = this.head;\n while (cur) {\n if (isMatch(cur)) return cur;\n cur = cur.next;\n }\n return undefined;\n }\n\n const predicate = this._ensurePredicate(elementNodeOrPredicate);\n let current = this.head;\n while (current) {\n if (predicate(current)) return current;\n current = current.next;\n }\n return undefined;\n }\n\n /**\n * Insert a new element/node at an index, shifting following nodes.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index.\n * @param newElementOrNode - Element or node to insert.\n * @returns True if inserted.\n */\n\n addAt(index: number, newElementOrNode: E | DoublyLinkedListNode<E>): boolean {\n if (index < 0 || index > this._length) return false;\n if (index === 0) return this.unshift(newElementOrNode);\n if (index === this._length) return this.push(newElementOrNode);\n\n const newNode = this._ensureNode(newElementOrNode);\n const prevNode = this.getNodeAt(index - 1)!;\n const nextNode = prevNode.next!;\n newNode.prev = prevNode;\n newNode.next = nextNode;\n prevNode.next = newNode;\n nextNode.prev = newNode;\n this._length++;\n return true;\n }\n\n /**\n * Insert a new element/node before an existing one.\n * @remarks Time O(N), Space O(1)\n * @param existingElementOrNode - Existing element or node.\n * @param newElementOrNode - Element or node to insert.\n * @returns True if inserted.\n */\n\n addBefore(\n existingElementOrNode: E | DoublyLinkedListNode<E>,\n newElementOrNode: E | DoublyLinkedListNode<E>\n ): boolean {\n const existingNode = this.isNode(existingElementOrNode)\n ? existingElementOrNode\n : this.getNode(existingElementOrNode);\n if (!existingNode) return false;\n\n const newNode = this._ensureNode(newElementOrNode);\n newNode.prev = existingNode.prev;\n if (existingNode.prev) existingNode.prev.next = newNode;\n newNode.next = existingNode;\n existingNode.prev = newNode;\n if (existingNode === this.head) this._head = newNode;\n this._length++;\n return true;\n }\n\n /**\n * Insert a new element/node after an existing one.\n * @remarks Time O(N), Space O(1)\n * @param existingElementOrNode - Existing element or node.\n * @param newElementOrNode - Element or node to insert.\n * @returns True if inserted.\n */\n\n addAfter(existingElementOrNode: E | DoublyLinkedListNode<E>, newElementOrNode: E | DoublyLinkedListNode<E>): boolean {\n const existingNode = this.isNode(existingElementOrNode)\n ? existingElementOrNode\n : this.getNode(existingElementOrNode);\n if (!existingNode) return false;\n\n const newNode = this._ensureNode(newElementOrNode);\n newNode.next = existingNode.next;\n if (existingNode.next) existingNode.next.prev = newNode;\n newNode.prev = existingNode;\n existingNode.next = newNode;\n if (existingNode === this.tail) this._tail = newNode;\n this._length++;\n return true;\n }\n\n /**\n * Set the element value at an index.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index.\n * @param value - New value.\n * @returns True if updated.\n */\n\n setAt(index: number, value: E): boolean {\n const node = this.getNodeAt(index);\n if (!node) return false;\n node.value = value;\n return true;\n }\n\n /**\n * Delete the element at an index.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index.\n * @returns Removed element or undefined.\n */\n\n deleteAt(index: number): E | undefined {\n if (index < 0 || index >= this._length) return;\n if (index === 0) return this.shift();\n if (index === this._length - 1) return this.pop();\n\n const removedNode = this.getNodeAt(index)!;\n const prevNode = removedNode.prev!;\n const nextNode = removedNode.next!;\n prevNode.next = nextNode;\n nextNode.prev = prevNode;\n this._length--;\n return removedNode.value;\n }\n\n /**\n * Delete the first match by value/node.\n * @remarks Time O(N), Space O(1)\n * @param [elementOrNode] - Element or node to remove.\n * @returns True if removed.\n */\n\n delete(elementOrNode: E | DoublyLinkedListNode<E> | undefined): boolean {\n const node = this.getNode(elementOrNode);\n if (!node) return false;\n\n if (node === this.head) this.shift();\n else if (node === this.tail) this.pop();\n else {\n const prevNode = node.prev!;\n const nextNode = node.next!;\n prevNode.next = nextNode;\n nextNode.prev = prevNode;\n this._length--;\n }\n return true;\n }\n\n /**\n * Check whether the list 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 * Remove all nodes and reset length.\n * @remarks Time O(N), Space O(1)\n * @returns void\n */\n\n clear(): void {\n this._head = undefined;\n this._tail = undefined;\n this._length = 0;\n }\n\n /**\n * Find the first value matching a predicate scanning forward.\n * @remarks Time O(N), Space O(1)\n * @param elementNodeOrPredicate - Element, node, or predicate to match.\n * @returns Matched value or undefined.\n */\n\n search(\n elementNodeOrPredicate: E | DoublyLinkedListNode<E> | ((node: DoublyLinkedListNode<E>) => boolean)\n ): E | undefined {\n const predicate = this._ensurePredicate(elementNodeOrPredicate);\n let current = this.head;\n while (current) {\n if (predicate(current)) return current.value;\n current = current.next;\n }\n return undefined;\n }\n\n /**\n * Find the first value matching a predicate scanning backward.\n * @remarks Time O(N), Space O(1)\n * @param elementNodeOrPredicate - Element, node, or predicate to match.\n * @returns Matched value or undefined.\n */\n\n getBackward(\n elementNodeOrPredicate: E | DoublyLinkedListNode<E> | ((node: DoublyLinkedListNode<E>) => boolean)\n ): E | undefined {\n const predicate = this._ensurePredicate(elementNodeOrPredicate);\n let current = this.tail;\n while (current) {\n if (predicate(current)) return current.value;\n current = current.prev;\n }\n return undefined;\n }\n\n /**\n * Reverse the list in place.\n * @remarks Time O(N), Space O(1)\n * @returns This list.\n */\n\n reverse(): this {\n let current = this.head;\n [this._head, this._tail] = [this.tail, this.head];\n while (current) {\n const next = current.next;\n [current.prev, current.next] = [current.next, current.prev];\n current = next;\n }\n return this;\n }\n\n /**\n * Set the equality comparator used to compare values.\n * @remarks Time O(1), Space O(1)\n * @param equals - Equality predicate (a, b) → boolean.\n * @returns This list.\n */\n\n setEquality(equals: (a: E, b: E) => boolean): this {\n this._equals = equals;\n return this;\n }\n\n /**\n * Deep clone this list (values are copied by reference).\n * @remarks Time O(N), Space O(N)\n * @returns A new list with the same element sequence.\n */\n\n 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 * Filter values into a new list of the same class.\n * @remarks Time O(N), Space O(N)\n * @param callback - Predicate (value, index, list) → boolean to keep value.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new list with kept values.\n */\n\n filter(callback: ElementCallback<E, R, boolean>, thisArg?: any): this {\n const out = this._createInstance({ toElementFn: this._toElementFn, maxLen: this._maxLen });\n let index = 0;\n for (const v of this) if (callback.call(thisArg, v, index++, this)) out.push(v);\n return out;\n }\n\n /**\n * Map values into a new list of the same class.\n * @remarks Time O(N), Space O(N)\n * @param callback - Mapping function (value, index, list) → newValue.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new list with mapped values.\n */\n\n mapSame(callback: ElementCallback<E, R, E>, thisArg?: any): this {\n const out = this._createInstance({ toElementFn: this._toElementFn, maxLen: this._maxLen });\n let index = 0;\n for (const v of this) {\n const mv = thisArg === undefined ? callback(v, index++, this) : callback.call(thisArg, v, index++, this);\n out.push(mv);\n }\n return out;\n }\n\n /**\n * Map values into a new list (possibly different element type).\n * @remarks Time O(N), Space O(N)\n * @template EM\n * @template RM\n * @param callback - Mapping function (value, index, list) → newElement.\n * @param [options] - Options for the output list (e.g., maxLen, toElementFn).\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new DoublyLinkedList with mapped values.\n */\n\n map<EM, RM>(\n callback: ElementCallback<E, R, EM>,\n options?: DoublyLinkedListOptions<EM, RM>,\n thisArg?: any\n ): DoublyLinkedList<EM, RM> {\n const out = this._createLike<EM, RM>([], { ...(options ?? {}), maxLen: this._maxLen });\n let index = 0;\n for (const v of this) out.push(callback.call(thisArg, v, index++, this));\n return out;\n }\n\n /**\n * (Protected) Create or return a node for the given input (node or raw element).\n * @remarks Time O(1), Space O(1)\n * @param elementOrNode - Element value or node to normalize.\n * @returns A DoublyLinkedListNode for the provided input.\n */\n\n protected _ensureNode(elementOrNode: E | DoublyLinkedListNode<E>) {\n if (this.isNode(elementOrNode)) return elementOrNode;\n return new DoublyLinkedListNode<E>(elementOrNode);\n }\n\n /**\n * (Protected) Normalize input into a predicate over nodes.\n * @remarks Time O(1), Space O(1)\n * @param elementNodeOrPredicate - Element, node, or node predicate.\n * @returns A predicate function taking a node and returning true/false.\n */\n\n protected _ensurePredicate(\n elementNodeOrPredicate: E | DoublyLinkedListNode<E> | ((node: DoublyLinkedListNode<E>) => boolean)\n ): (node: DoublyLinkedListNode<E>) => boolean {\n if (this.isNode(elementNodeOrPredicate)) {\n const target = elementNodeOrPredicate;\n return (node: DoublyLinkedListNode<E>) => node === target;\n }\n if (typeof elementNodeOrPredicate === 'function') {\n return elementNodeOrPredicate as (node: DoublyLinkedListNode<E>) => boolean;\n }\n const value = elementNodeOrPredicate as E;\n return (node: DoublyLinkedListNode<E>) => this._equals(node.value, value);\n }\n\n /**\n * (Protected) Get the previous node of a given node.\n * @remarks Time O(1), Space O(1)\n * @param node - A node in the list.\n * @returns Previous node or undefined.\n */\n\n protected _getPrevNode(node: DoublyLinkedListNode<E>): DoublyLinkedListNode<E> | undefined {\n return node.prev;\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 list instance.\n */\n\n protected override _createInstance(options?: LinearBaseOptions<E, R>): this {\n const Ctor = this.constructor as new (\n elements?: Iterable<E> | Iterable<R> | Iterable<DoublyLinkedListNode<E>>,\n options?: DoublyLinkedListOptions<E, R>\n ) => this;\n return new Ctor([], options as DoublyLinkedListOptions<E, R> | undefined);\n }\n\n /**\n * (Protected) Create a like-kind instance 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 list.\n * @param [options] - Options forwarded to the constructor.\n * @returns A like-kind DoublyLinkedList instance.\n */\n\n protected _createLike<EM = E, RM = R>(\n elements: Iterable<EM> | Iterable<RM> | Iterable<DoublyLinkedListNode<EM>> = [],\n options?: DoublyLinkedListOptions<EM, RM>\n ): DoublyLinkedList<EM, RM> {\n const Ctor = this.constructor as new (\n elements?: Iterable<EM> | Iterable<RM> | Iterable<DoublyLinkedListNode<EM>>,\n options?: DoublyLinkedListOptions<EM, RM>\n ) => DoublyLinkedList<EM, RM>;\n return new Ctor(elements, options);\n }\n\n protected *_getIterator(): IterableIterator<E> {\n let current = this.head;\n while (current) {\n yield current.value;\n current = current.next;\n }\n }\n\n protected *_getReverseIterator(): IterableIterator<E> {\n let current = this.tail;\n while (current) {\n yield current.value;\n current = current.prev;\n }\n }\n\n protected *_getNodeIterator(): IterableIterator<DoublyLinkedListNode<E>> {\n let current = this.head;\n while (current) {\n yield current;\n current = current.next;\n }\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 */\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 { 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;;;ACaO,MAAe,sBAAf,MAAgE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAU3D,YAAY,SAA4C;AAclE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,0BAAU;AAbR,UAAI,SAAS;AACX,cAAM,EAAE,YAAY,IAAI;AACxB,YAAI,OAAO,gBAAgB,WAAY,MAAK,eAAe;AAAA,iBAClD,YAAa,OAAM,IAAI,UAAU,qCAAqC;AAAA,MACjF;AAAA,IACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAiBA,IAAI,cAAkD;AACpD,aAAO,KAAK;AAAA,IACd;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAWA,EAAE,OAAO,QAAQ,KAAK,MAAsC;AAC1D,aAAO,KAAK,aAAa,GAAG,IAAI;AAAA,IAClC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IASA,CAAC,SAA8B;AAC7B,iBAAW,QAAQ,KAAM,OAAM;AAAA,IACj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M,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":["DFSOperation"]}
@@ -0,0 +1,9 @@
1
+ "use strict";var doublyLinkedListTyped=(()=>{var d=Object.defineProperty;var _=Object.getOwnPropertyDescriptor;var N=Object.getOwnPropertyNames;var R=Object.prototype.hasOwnProperty;var w=(o,i,e)=>i in o?d(o,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[i]=e;var D=(o,i)=>{for(var e in i)d(o,e,{get:i[e],enumerable:!0})},I=(o,i,e,t)=>{if(i&&typeof i=="object"||typeof i=="function")for(let n of N(i))!R.call(o,n)&&n!==e&&d(o,n,{get:()=>i[n],enumerable:!(t=_(i,n))||t.enumerable});return o};var M=o=>I(d({},"__esModule",{value:!0}),o);var a=(o,i,e)=>w(o,typeof i!="symbol"?i+"":i,e);var T={};D(T,{DFSOperation:()=>y,DoublyLinkedList:()=>p,DoublyLinkedListNode:()=>h,Range:()=>g});var c=class{constructor(i){a(this,"_toElementFn");if(i){let{toElementFn:e}=i;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](...i){yield*this._getIterator(...i)}*values(){for(let i of this)yield i}every(i,e){let t=0;for(let n of this)if(e===void 0){if(!i(n,t++,this))return!1}else if(!i.call(e,n,t++,this))return!1;return!0}some(i,e){let t=0;for(let n of this)if(e===void 0){if(i(n,t++,this))return!0}else if(i.call(e,n,t++,this))return!0;return!1}forEach(i,e){let t=0;for(let n of this)e===void 0?i(n,t++,this):i.call(e,n,t++,this)}find(i,e){let t=0;for(let n of this)if(e===void 0){if(i(n,t++,this))return n}else if(i.call(e,n,t++,this))return n}has(i){for(let e of this)if(e===i)return!0;return!1}reduce(i,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=i(r,s,t++,this);return r}toArray(){return[...this]}toVisual(){return[...this]}print(){console.log(this.toVisual())}};var f=class{constructor(i){a(this,"_value");a(this,"_next");this._value=i,this._next=void 0}get value(){return this._value}set value(i){this._value=i}get next(){return this._next}set next(i){this._next=i}},E=class o extends c{constructor(e){super(e);a(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 o?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 l=this.deleteAt(e);l!==void 0&&r.push(l)}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}},b=class extends E{constructor(i){if(super(i),i){let{maxLen:e}=i;typeof e=="number"&&e>0&&e%1===0&&(this._maxLen=e)}}indexOf(i,e=0){let t=this._getIterator(),n=t.next(),r=0;for(;r<e;)n=t.next(),r++;for(;!n.done;){if(n.value===i)return r;n=t.next(),r++}return-1}lastIndexOf(i,e=this.length-1){let t=this._getReverseIterator(),n=t.next(),r=this.length-1;for(;r>e;)n=t.next(),r--;for(;!n.done;){if(n.value===i)return r;n=t.next(),r--}return-1}concat(...i){let e=this.clone();for(let t of i)t instanceof E?e.pushMany(t):e.push(t);return e}slice(i=0,e=this.length){i=i<0?this.length+i:i,e=e<0?this.length+e:e;let t=this._createInstance(),n=this._getIterator(),r=n.next(),s=0;for(;s<i;)r=n.next(),s++;for(let l=i;l<e;l++)t.push(r.value),r=n.next();return t}splice(i,e=0,...t){let n=this._createInstance();i=i<0?this.length+i:i,i=Math.max(0,Math.min(i,this.length)),e=Math.max(0,e);let r=0,s,l,m=this._getNodeIterator();for(let u of m){if(r===i){s=u;break}l=u,r++}for(let u=0;u<e&&s;u++){n.push(s.value);let v=s.next;this.delete(s),s=v}for(let u=0;u<t.length;u++)l?(this.addAfter(l,t[u]),l=l.next):(this.addAt(0,t[u]),l=this._getNodeIterator().next().value);return n}reduceRight(i,e){let t=e!=null?e:0,n=this.length-1;for(let r of this._getReverseIterator())t=i(t,r,n--,this);return t}};var h=class extends f{constructor(e){super(e);a(this,"_next");a(this,"_prev");this._value=e,this._next=void 0,this._prev=void 0}get next(){return this._next}set next(e){this._next=e}get prev(){return this._prev}set prev(e){this._prev=e}},p=class extends b{constructor(e=[],t){super(t);a(this,"_equals",Object.is);a(this,"_head");a(this,"_tail");a(this,"_length",0);this._head=void 0,this._tail=void 0,this._length=0,t!=null&&t.maxLen&&Number.isInteger(t.maxLen)&&t.maxLen>0&&(this._maxLen=t.maxLen),this.pushMany(e)}get head(){return this._head}get tail(){return this._tail}get length(){return this._length}get first(){var e;return(e=this.head)==null?void 0:e.value}get last(){var e;return(e=this.tail)==null?void 0:e.value}static fromArray(e){return new this(e)}isNode(e){return e instanceof h}push(e){let t=this._ensureNode(e);return this.head?(t.prev=this.tail,this.tail.next=t,this._tail=t):(this._head=t,this._tail=t),this._length++,this._maxLen>0&&this.length>this._maxLen&&this.shift(),!0}pop(){if(!this.tail)return;let e=this.tail;return this.head===this.tail?(this._head=void 0,this._tail=void 0):(this._tail=e.prev,this.tail.next=void 0),this._length--,e.value}shift(){if(!this.head)return;let e=this.head;return this.head===this.tail?(this._head=void 0,this._tail=void 0):(this._head=e.next,this.head.prev=void 0),this._length--,e.value}unshift(e){let t=this._ensureNode(e);return this.head?(t.next=this.head,this.head.prev=t,this._head=t):(this._head=t,this._tail=t),this._length++,this._maxLen>0&&this._length>this._maxLen&&this.pop(),!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}unshiftMany(e){let t=[];for(let n of e)this.toElementFn?t.push(this.unshift(this.toElementFn(n))):t.push(this.unshift(n));return t}at(e){if(e<0||e>=this._length)return;let t=this.head;for(let n=0;n<e;n++)t=t.next;return t.value}getNodeAt(e){if(e<0||e>=this._length)return;let t=this.head;for(let n=0;n<e;n++)t=t.next;return t}getNode(e){if(e===void 0)return;if(this.isNode(e)){let r=e,s=this.head;for(;s;){if(s===r)return r;s=s.next}let l=m=>this._equals(m.value,r.value);for(s=this.head;s;){if(l(s))return s;s=s.next}return}let t=this._ensurePredicate(e),n=this.head;for(;n;){if(t(n))return n;n=n.next}}addAt(e,t){if(e<0||e>this._length)return!1;if(e===0)return this.unshift(t);if(e===this._length)return this.push(t);let n=this._ensureNode(t),r=this.getNodeAt(e-1),s=r.next;return n.prev=r,n.next=s,r.next=n,s.prev=n,this._length++,!0}addBefore(e,t){let n=this.isNode(e)?e:this.getNode(e);if(!n)return!1;let r=this._ensureNode(t);return r.prev=n.prev,n.prev&&(n.prev.next=r),r.next=n,n.prev=r,n===this.head&&(this._head=r),this._length++,!0}addAfter(e,t){let n=this.isNode(e)?e:this.getNode(e);if(!n)return!1;let r=this._ensureNode(t);return r.next=n.next,n.next&&(n.next.prev=r),r.prev=n,n.next=r,n===this.tail&&(this._tail=r),this._length++,!0}setAt(e,t){let n=this.getNodeAt(e);return n?(n.value=t,!0):!1}deleteAt(e){if(e<0||e>=this._length)return;if(e===0)return this.shift();if(e===this._length-1)return this.pop();let t=this.getNodeAt(e),n=t.prev,r=t.next;return n.next=r,r.prev=n,this._length--,t.value}delete(e){let t=this.getNode(e);if(!t)return!1;if(t===this.head)this.shift();else if(t===this.tail)this.pop();else{let n=t.prev,r=t.next;n.next=r,r.prev=n,this._length--}return!0}isEmpty(){return this._length===0}clear(){this._head=void 0,this._tail=void 0,this._length=0}search(e){let t=this._ensurePredicate(e),n=this.head;for(;n;){if(t(n))return n.value;n=n.next}}getBackward(e){let t=this._ensurePredicate(e),n=this.tail;for(;n;){if(t(n))return n.value;n=n.prev}}reverse(){let e=this.head;for([this._head,this._tail]=[this.tail,this.head];e;){let t=e.next;[e.prev,e.next]=[e.next,e.prev],e=t}return this}setEquality(e){return this._equals=e,this}clone(){let e=this._createInstance({toElementFn:this._toElementFn,maxLen:this._maxLen});for(let t of this)e.push(t);return e}filter(e,t){let n=this._createInstance({toElementFn:this._toElementFn,maxLen:this._maxLen}),r=0;for(let s of this)e.call(t,s,r++,this)&&n.push(s);return n}mapSame(e,t){let n=this._createInstance({toElementFn:this._toElementFn,maxLen:this._maxLen}),r=0;for(let s of this){let l=t===void 0?e(s,r++,this):e.call(t,s,r++,this);n.push(l)}return n}map(e,t,n){let r=this._createLike([],{...t!=null?t:{},maxLen:this._maxLen}),s=0;for(let l of this)r.push(e.call(n,l,s++,this));return r}_ensureNode(e){return this.isNode(e)?e:new h(e)}_ensurePredicate(e){if(this.isNode(e)){let n=e;return r=>r===n}if(typeof e=="function")return e;let t=e;return n=>this._equals(n.value,t)}_getPrevNode(e){return e.prev}_createInstance(e){let t=this.constructor;return new t([],e)}_createLike(e=[],t){let n=this.constructor;return new n(e,t)}*_getIterator(){let e=this.head;for(;e;)yield e.value,e=e.next}*_getReverseIterator(){let e=this.tail;for(;e;)yield e.value,e=e.prev}*_getNodeIterator(){let e=this.head;for(;e;)yield e,e=e.next}};function L(o){let i=typeof o;return i==="number"?!0:i==="bigint"||i==="string"||i==="boolean"}function k(o){if(typeof o.valueOf=="function"){let i=o.valueOf();if(i!==o){if(L(i))return i;if(typeof i=="object"&&i!==null)return k(i)}}if(typeof o.toString=="function"){let i=o.toString();if(i!=="[object Object]")return i}return null}function x(o,i=!1){if(o==null)return!1;if(L(o))return!0;if(typeof o!="object")return!1;if(o instanceof Date||i)return!0;let e=k(o);return e==null?!1:L(e)}var y=(e=>(e[e.VISIT=0]="VISIT",e[e.PROCESS=1]="PROCESS",e))(y||{}),g=class{constructor(i,e,t=!0,n=!0){this.low=i;this.high=e;this.includeLow=t;this.includeHigh=n;if(!(x(i)&&x(e)))throw new RangeError("low or high is not comparable");if(i>e)throw new RangeError("low must be less than or equal to high")}isInRange(i,e){let t=this.includeLow?e(i,this.low)>=0:e(i,this.low)>0,n=this.includeHigh?e(i,this.high)<=0:e(i,this.high)<0;return t&&n}};return M(T);})();
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=doubly-linked-list-typed.min.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/index.ts","../../src/data-structures/base/iterable-element-base.ts","../../src/data-structures/base/linear-base.ts","../../src/data-structures/linked-list/doubly-linked-list.ts","../../src/utils/utils.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/linked-list/doubly-linked-list';\nexport * from './types/data-structures/linked-list/doubly-linked-list';\nexport * from './types/common';\nexport * from './types/utils';\nexport * from './common';","import type { ElementCallback, IterableElementBaseOptions, ReduceElementCallback } from '../../types';\n\n/**\n * Base class that makes a data structure iterable and provides common\n * element-wise utilities (e.g., map/filter/reduce/find).\n *\n * @template E The public element type yielded by the structure.\n * @template R The underlying \"raw\" element type used internally or by converters.\n *\n * @remarks\n * This class implements the JavaScript iteration protocol (via `Symbol.iterator`)\n * and offers array-like helpers with predictable time/space complexity.\n */\nexport abstract class IterableElementBase<E, R> implements Iterable<E> {\n /**\n * Create a new iterable base.\n *\n * @param options Optional behavior overrides. When provided, a `toElementFn`\n * is used to convert a raw element (`R`) into a public element (`E`).\n *\n * @remarks\n * Time O(1), Space O(1).\n */\n protected constructor(options?: IterableElementBaseOptions<E, R>) {\n if (options) {\n const { toElementFn } = options;\n if (typeof toElementFn === 'function') this._toElementFn = toElementFn;\n else if (toElementFn) throw new TypeError('toElementFn must be a function type');\n }\n }\n\n /**\n * The converter used to transform a raw element (`R`) into a public element (`E`).\n *\n * @remarks\n * Time O(1), Space O(1).\n */\n protected _toElementFn?: (rawElement: R) => E;\n\n /**\n * Exposes the current `toElementFn`, if configured.\n *\n * @returns The converter function or `undefined` when not set.\n * @remarks\n * Time O(1), Space O(1).\n */\n get toElementFn(): ((rawElement: R) => E) | undefined {\n return this._toElementFn;\n }\n\n /**\n * Returns an iterator over the structure's elements.\n *\n * @param args Optional iterator arguments forwarded to the internal iterator.\n * @returns An `IterableIterator<E>` that yields the elements in traversal order.\n *\n * @remarks\n * Producing the iterator is O(1); consuming the entire iterator is Time O(n) with O(1) extra space.\n */\n *[Symbol.iterator](...args: unknown[]): IterableIterator<E> {\n yield* this._getIterator(...args);\n }\n\n /**\n * Returns an iterator over the values (alias of the default iterator).\n *\n * @returns An `IterableIterator<E>` over all elements.\n * @remarks\n * Creating the iterator is O(1); full iteration is Time O(n), Space O(1).\n */\n *values(): IterableIterator<E> {\n for (const item of this) yield item;\n }\n\n /**\n * Tests whether all elements satisfy the predicate.\n *\n * @template TReturn\n * @param predicate Function invoked for each element with signature `(value, index, self)`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns `true` if every element passes; otherwise `false`.\n *\n * @remarks\n * Time O(n) in the worst case; may exit early when the first failure is found. Space O(1).\n */\n every(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): boolean {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n if (!predicate(item, index++, this)) return false;\n } else {\n const fn = predicate as (this: unknown, v: E, i: number, self: this) => boolean;\n if (!fn.call(thisArg, item, index++, this)) return false;\n }\n }\n return true;\n }\n\n /**\n * Tests whether at least one element satisfies the predicate.\n *\n * @param predicate Function invoked for each element with signature `(value, index, self)`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns `true` if any element passes; otherwise `false`.\n *\n * @remarks\n * Time O(n) in the worst case; may exit early on first success. Space O(1).\n */\n some(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): boolean {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n if (predicate(item, index++, this)) return true;\n } else {\n const fn = predicate as (this: unknown, v: E, i: number, self: this) => boolean;\n if (fn.call(thisArg, item, index++, this)) return true;\n }\n }\n return false;\n }\n\n /**\n * Invokes a callback for each element in iteration order.\n *\n * @param callbackfn Function invoked per element with signature `(value, index, self)`.\n * @param thisArg Optional `this` binding for the callback.\n * @returns `void`.\n *\n * @remarks\n * Time O(n), Space O(1).\n */\n forEach(callbackfn: ElementCallback<E, R, void>, thisArg?: unknown): void {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n callbackfn(item, index++, this);\n } else {\n const fn = callbackfn as (this: unknown, v: E, i: number, self: this) => void;\n fn.call(thisArg, item, index++, this);\n }\n }\n }\n\n /**\n * Finds the first element that satisfies the predicate and returns it.\n *\n * @overload\n * Finds the first element of type `S` (a subtype of `E`) that satisfies the predicate and returns it.\n * @template S\n * @param predicate Type-guard predicate: `(value, index, self) => value is S`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns The matched element typed as `S`, or `undefined` if not found.\n *\n * @overload\n * @param predicate Boolean predicate: `(value, index, self) => boolean`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns The first matching element as `E`, or `undefined` if not found.\n *\n * @remarks\n * Time O(n) in the worst case; may exit early on the first match. Space O(1).\n */\n find<S extends E>(predicate: ElementCallback<E, R, S>, thisArg?: unknown): S | undefined;\n find(predicate: ElementCallback<E, R, unknown>, thisArg?: unknown): E | undefined;\n\n // Implementation signature\n find(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): E | undefined {\n let index = 0;\n for (const item of this) {\n if (thisArg === undefined) {\n if (predicate(item, index++, this)) return item;\n } else {\n const fn = predicate as (this: unknown, v: E, i: number, self: this) => boolean;\n if (fn.call(thisArg, item, index++, this)) return item;\n }\n }\n return;\n }\n\n /**\n * Checks whether a strictly-equal element exists in the structure.\n *\n * @param element The element to test with `===` equality.\n * @returns `true` if an equal element is found; otherwise `false`.\n *\n * @remarks\n * Time O(n) in the worst case. Space O(1).\n */\n has(element: E): boolean {\n for (const ele of this) if (ele === element) return true;\n return false;\n }\n\n reduce(callbackfn: ReduceElementCallback<E, R>): E;\n reduce(callbackfn: ReduceElementCallback<E, R>, initialValue: E): E;\n reduce<U>(callbackfn: ReduceElementCallback<E, R, U>, initialValue: U): U;\n\n /**\n * Reduces all elements to a single accumulated value.\n *\n * @overload\n * @param callbackfn Reducer of signature `(acc, value, index, self) => nextAcc`. The first element is used as the initial accumulator.\n * @returns The final accumulated value typed as `E`.\n *\n * @overload\n * @param callbackfn Reducer of signature `(acc, value, index, self) => nextAcc`.\n * @param initialValue The initial accumulator value of type `E`.\n * @returns The final accumulated value typed as `E`.\n *\n * @overload\n * @template U The accumulator type when it differs from `E`.\n * @param callbackfn Reducer of signature `(acc: U, value, index, self) => U`.\n * @param initialValue The initial accumulator value of type `U`.\n * @returns The final accumulated value typed as `U`.\n *\n * @remarks\n * Time O(n), Space O(1). Throws if called on an empty structure without `initialValue`.\n */\n reduce<U>(callbackfn: ReduceElementCallback<E, R, U>, initialValue?: U): U {\n let index = 0;\n const iter = this[Symbol.iterator]();\n let acc: U;\n\n if (arguments.length >= 2) {\n acc = initialValue as U;\n } else {\n const first = iter.next();\n if (first.done) throw new TypeError('Reduce of empty structure with no initial value');\n acc = first.value as unknown as U;\n index = 1;\n }\n\n for (const value of iter as unknown as Iterable<E>) {\n acc = callbackfn(acc, value, index++, this);\n }\n return acc;\n }\n\n /**\n * Materializes the elements into a new array.\n *\n * @returns A shallow array copy of the iteration order.\n * @remarks\n * Time O(n), Space O(n).\n */\n toArray(): E[] {\n return [...this];\n }\n\n /**\n * Returns a representation of the structure suitable for quick visualization.\n * Defaults to an array of elements; subclasses may override to provide richer visuals.\n *\n * @returns A visual representation (array by default).\n * @remarks\n * Time O(n), Space O(n).\n */\n toVisual(): E[] {\n return [...this];\n }\n\n /**\n * Prints `toVisual()` to the console. Intended for quick debugging.\n *\n * @returns `void`.\n * @remarks\n * Time O(n) due to materialization, Space O(n) for the intermediate representation.\n */\n print(): void {\n console.log(this.toVisual());\n }\n\n /**\n * Indicates whether the structure currently contains no elements.\n *\n * @returns `true` if empty; otherwise `false`.\n * @remarks\n * Expected Time O(1), Space O(1) for most implementations.\n */\n abstract isEmpty(): boolean;\n\n /**\n * Removes all elements from the structure.\n *\n * @returns `void`.\n * @remarks\n * Expected Time O(1) or O(n) depending on the implementation; Space O(1).\n */\n abstract clear(): void;\n\n /**\n * Creates a structural copy with the same element values and configuration.\n *\n * @returns A clone of the current instance (same concrete type).\n * @remarks\n * Expected Time O(n) to copy elements; Space O(n).\n */\n abstract clone(): this;\n\n /**\n * Maps each element to a new element and returns a new iterable structure.\n *\n * @template EM The mapped element type.\n * @template RM The mapped raw element type used internally by the target structure.\n * @param callback Function with signature `(value, index, self) => mapped`.\n * @param options Optional options for the returned structure, including its `toElementFn`.\n * @param thisArg Optional `this` binding for the callback.\n * @returns A new `IterableElementBase<EM, RM>` containing mapped elements.\n *\n * @remarks\n * Time O(n), Space O(n).\n */\n abstract map<EM, RM>(\n callback: ElementCallback<E, R, EM>,\n options?: IterableElementBaseOptions<EM, RM>,\n thisArg?: unknown\n ): IterableElementBase<EM, RM>;\n\n /**\n * Maps each element to the same element type and returns the same concrete structure type.\n *\n * @param callback Function with signature `(value, index, self) => mappedValue`.\n * @param thisArg Optional `this` binding for the callback.\n * @returns A new instance of the same concrete type with mapped elements.\n *\n * @remarks\n * Time O(n), Space O(n).\n */\n abstract mapSame(callback: ElementCallback<E, R, E>, thisArg?: unknown): this;\n\n /**\n * Filters elements using the provided predicate and returns the same concrete structure type.\n *\n * @param predicate Function with signature `(value, index, self) => boolean`.\n * @param thisArg Optional `this` binding for the predicate.\n * @returns A new instance of the same concrete type containing only elements that pass the predicate.\n *\n * @remarks\n * Time O(n), Space O(k) where `k` is the number of kept elements.\n */\n abstract filter(predicate: ElementCallback<E, R, boolean>, thisArg?: unknown): this;\n\n /**\n * Internal iterator factory used by the default iterator.\n *\n * @param args Optional iterator arguments.\n * @returns An iterator over elements.\n *\n * @remarks\n * Implementations should yield in O(1) per element with O(1) extra space when possible.\n */\n protected abstract _getIterator(...args: unknown[]): IterableIterator<E>;\n}\n","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 { DoublyLinkedListOptions, ElementCallback, LinearBaseOptions } from '../../types';\nimport { LinearLinkedBase, LinkedListNode } from '../base/linear-base';\n\n/**\n * Node of a doubly linked list; stores value and prev/next links.\n * @remarks Time O(1), Space O(1)\n * @template E\n */\nexport class DoublyLinkedListNode<E = any> extends LinkedListNode<E> {\n /**\n * Create a node.\n * @remarks Time O(1), Space O(1)\n * @param value - Element value to store.\n * @returns New node instance.\n */\n\n constructor(value: E) {\n super(value);\n this._value = value;\n this._next = undefined;\n this._prev = undefined;\n }\n\n protected override _next: DoublyLinkedListNode<E> | undefined;\n\n /**\n * Get the next node link.\n * @remarks Time O(1), Space O(1)\n * @returns Next node or undefined.\n */\n\n override get next(): DoublyLinkedListNode<E> | undefined {\n return this._next;\n }\n\n /**\n * Set the next node link.\n * @remarks Time O(1), Space O(1)\n * @param value - Next node or undefined.\n * @returns void\n */\n\n override set next(value: DoublyLinkedListNode<E> | undefined) {\n this._next = value;\n }\n\n protected _prev: DoublyLinkedListNode<E> | undefined;\n\n /**\n * Get the previous node link.\n * @remarks Time O(1), Space O(1)\n * @returns Previous node or undefined.\n */\n\n get prev(): DoublyLinkedListNode<E> | undefined {\n return this._prev;\n }\n\n /**\n * Set the previous node link.\n * @remarks Time O(1), Space O(1)\n * @param value - Previous node or undefined.\n * @returns void\n */\n\n set prev(value: DoublyLinkedListNode<E> | undefined) {\n this._prev = value;\n }\n}\n\n/**\n * Doubly linked list with O(1) push/pop/unshift/shift and linear scans.\n * @remarks Time O(1), Space O(1)\n * @template E\n * @template R\n * 1. Node Structure: Each node contains three parts: a data field, a pointer (or reference) to the previous node, and a pointer to the next node. This structure allows traversal of the linked list in both directions.\n * 2. Bidirectional Traversal: Unlike singly linked lists, doubly linked lists can be easily traversed forwards or backwards. This makes insertions and deletions in the list more flexible and efficient.\n * 3. No Centralized Index: Unlike arrays, elements in a linked list are not stored contiguously, so there is no centralized index. Accessing elements in a linked list typically requires traversing from the head or tail node.\n * 4. High Efficiency in Insertion and Deletion: Adding or removing elements in a linked list does not require moving other elements, making these operations more efficient than in arrays.\n * Caution: Although our linked list classes provide methods such as at, setAt, addAt, and indexOf that are based on array indices, their time complexity, like that of the native Array.lastIndexOf, is 𝑂(𝑛). If you need to use these methods frequently, you might want to consider other data structures, such as Deque or Queue (designed for random access). Similarly, since the native Array.shift method has a time complexity of 𝑂(𝑛), using an array to simulate a queue can be inefficient. In such cases, you should use Queue or Deque, as these data structures leverage deferred array rearrangement, effectively reducing the average time complexity to 𝑂(1).\n * @example\n * // text editor operation history\n * const actions = [\n * { type: 'insert', content: 'first line of text' },\n * { type: 'insert', content: 'second line of text' },\n * { type: 'delete', content: 'delete the first line' }\n * ];\n * const editorHistory = new DoublyLinkedList<{ type: string; content: string }>(actions);\n *\n * console.log(editorHistory.last?.type); // 'delete'\n * console.log(editorHistory.pop()?.content); // 'delete the first line'\n * console.log(editorHistory.last?.type); // 'insert'\n * @example\n * // Browser history\n * const browserHistory = new DoublyLinkedList<string>();\n *\n * browserHistory.push('home page');\n * browserHistory.push('search page');\n * browserHistory.push('details page');\n *\n * console.log(browserHistory.last); // 'details page'\n * console.log(browserHistory.pop()); // 'details page'\n * console.log(browserHistory.last); // 'search page'\n * @example\n * // Use DoublyLinkedList to implement music player\n * // Define the Song interface\n * interface Song {\n * title: string;\n * artist: string;\n * duration: number; // duration in seconds\n * }\n *\n * class Player {\n * private playlist: DoublyLinkedList<Song>;\n * private currentSong: ReturnType<typeof this.playlist.getNodeAt> | undefined;\n *\n * constructor(songs: Song[]) {\n * this.playlist = new DoublyLinkedList<Song>();\n * songs.forEach(song => this.playlist.push(song));\n * this.currentSong = this.playlist.head;\n * }\n *\n * // Play the next song in the playlist\n * playNext(): Song | undefined {\n * if (!this.currentSong?.next) {\n * this.currentSong = this.playlist.head; // Loop to the first song\n * } else {\n * this.currentSong = this.currentSong.next;\n * }\n * return this.currentSong?.value;\n * }\n *\n * // Play the previous song in the playlist\n * playPrevious(): Song | undefined {\n * if (!this.currentSong?.prev) {\n * this.currentSong = this.playlist.tail; // Loop to the last song\n * } else {\n * this.currentSong = this.currentSong.prev;\n * }\n * return this.currentSong?.value;\n * }\n *\n * // Get the current song\n * getCurrentSong(): Song | undefined {\n * return this.currentSong?.value;\n * }\n *\n * // Loop through the playlist twice\n * loopThroughPlaylist(): Song[] {\n * const playedSongs: Song[] = [];\n * const initialNode = this.currentSong;\n *\n * // Loop through the playlist twice\n * for (let i = 0; i < this.playlist.length * 2; i++) {\n * playedSongs.push(this.currentSong!.value);\n * this.currentSong = this.currentSong!.next || this.playlist.head; // Loop back to the start if needed\n * }\n *\n * // Reset the current song to the initial song\n * this.currentSong = initialNode;\n * return playedSongs;\n * }\n * }\n *\n * const songs = [\n * { title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 },\n * { title: 'Hotel California', artist: 'Eagles', duration: 391 },\n * { title: 'Shape of You', artist: 'Ed Sheeran', duration: 233 },\n * { title: 'Billie Jean', artist: 'Michael Jackson', duration: 294 }\n * ];\n * let player = new Player(songs);\n * // should play the next song\n * player = new Player(songs);\n * const firstSong = player.getCurrentSong();\n * const nextSong = player.playNext();\n *\n * // Expect the next song to be \"Hotel California by Eagles\"\n * console.log(nextSong); // { title: 'Hotel California', artist: 'Eagles', duration: 391 }\n * console.log(firstSong); // { title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 }\n *\n * // should play the previous song\n * player = new Player(songs);\n * player.playNext(); // Move to the second song\n * const currentSong = player.getCurrentSong();\n * const previousSong = player.playPrevious();\n *\n * // Expect the previous song to be \"Bohemian Rhapsody by Queen\"\n * console.log(previousSong); // { title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 }\n * console.log(currentSong); // { title: 'Hotel California', artist: 'Eagles', duration: 391 }\n *\n * // should loop to the first song when playing next from the last song\n * player = new Player(songs);\n * player.playNext(); // Move to the second song\n * player.playNext(); // Move to the third song\n * player.playNext(); // Move to the fourth song\n *\n * const nextSongToFirst = player.playNext(); // Should loop to the first song\n *\n * // Expect the next song to be \"Bohemian Rhapsody by Queen\"\n * console.log(nextSongToFirst); // { title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 }\n *\n * // should loop to the last song when playing previous from the first song\n * player = new Player(songs);\n * player.playNext(); // Move to the first song\n * player.playNext(); // Move to the second song\n * player.playNext(); // Move to the third song\n * player.playNext(); // Move to the fourth song\n *\n * const previousToLast = player.playPrevious(); // Should loop to the last song\n *\n * // Expect the previous song to be \"Billie Jean by Michael Jackson\"\n * console.log(previousToLast); // { title: 'Billie Jean', artist: 'Michael Jackson', duration: 294 }\n *\n * // should loop through the entire playlist\n * player = new Player(songs);\n * const playedSongs = player.loopThroughPlaylist();\n *\n * // The expected order of songs for two loops\n * console.log(playedSongs); // [\n * // { title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 },\n * // { title: 'Hotel California', artist: 'Eagles', duration: 391 },\n * // { title: 'Shape of You', artist: 'Ed Sheeran', duration: 233 },\n * // { title: 'Billie Jean', artist: 'Michael Jackson', duration: 294 },\n * // { title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 },\n * // { title: 'Hotel California', artist: 'Eagles', duration: 391 },\n * // { title: 'Shape of You', artist: 'Ed Sheeran', duration: 233 },\n * // { title: 'Billie Jean', artist: 'Michael Jackson', duration: 294 }\n * // ]\n * @example\n * // Use DoublyLinkedList to implement LRU cache\n * interface CacheEntry<K, V> {\n * key: K;\n * value: V;\n * }\n *\n * class LRUCache<K = string, V = any> {\n * private readonly capacity: number;\n * private list: DoublyLinkedList<CacheEntry<K, V>>;\n * private map: Map<K, DoublyLinkedListNode<CacheEntry<K, V>>>;\n *\n * constructor(capacity: number) {\n * if (capacity <= 0) {\n * throw new Error('lru cache capacity must be greater than 0');\n * }\n * this.capacity = capacity;\n * this.list = new DoublyLinkedList<CacheEntry<K, V>>();\n * this.map = new Map<K, DoublyLinkedListNode<CacheEntry<K, V>>>();\n * }\n *\n * // Get the current cache length\n * get length(): number {\n * return this.list.length;\n * }\n *\n * // Check if it is empty\n * get isEmpty(): boolean {\n * return this.list.isEmpty();\n * }\n *\n * // Get cached value\n * get(key: K): V | undefined {\n * const node = this.map.get(key);\n *\n * if (!node) return undefined;\n *\n * // Move the visited node to the head of the linked list (most recently used)\n * this.moveToFront(node);\n *\n * return node.value.value;\n * }\n *\n * // Set cache value\n * set(key: K, value: V): void {\n * // Check if it already exists\n * const node = this.map.get(key);\n *\n * if (node) {\n * // Update value and move to head\n * node.value.value = value;\n * this.moveToFront(node);\n * return;\n * }\n *\n * // Check capacity\n * if (this.list.length >= this.capacity) {\n * // Delete the least recently used element (the tail of the linked list)\n * const removedNode = this.list.tail;\n * if (removedNode) {\n * this.map.delete(removedNode.value.key);\n * this.list.pop();\n * }\n * }\n *\n * // Create new node and add to head\n * const newEntry: CacheEntry<K, V> = { key, value };\n * this.list.unshift(newEntry);\n *\n * // Save node reference in map\n * const newNode = this.list.head;\n * if (newNode) {\n * this.map.set(key, newNode);\n * }\n * }\n *\n * // Delete specific key\n * delete(key: K): boolean {\n * const node = this.map.get(key);\n * if (!node) return false;\n *\n * // Remove from linked list\n * this.list.delete(node);\n * // Remove from map\n * this.map.delete(key);\n *\n * return true;\n * }\n *\n * // Clear cache\n * clear(): void {\n * this.list.clear();\n * this.map.clear();\n * }\n *\n * // Move the node to the head of the linked list\n * private moveToFront(node: DoublyLinkedListNode<CacheEntry<K, V>>): void {\n * this.list.delete(node);\n * this.list.unshift(node.value);\n * }\n * }\n *\n * // should set and get values correctly\n * const cache = new LRUCache<string, number>(3);\n * cache.set('a', 1);\n * cache.set('b', 2);\n * cache.set('c', 3);\n *\n * console.log(cache.get('a')); // 1\n * console.log(cache.get('b')); // 2\n * console.log(cache.get('c')); // 3\n *\n * // The least recently used element should be evicted when capacity is exceeded\n * cache.clear();\n * cache.set('a', 1);\n * cache.set('b', 2);\n * cache.set('c', 3);\n * cache.set('d', 4); // This will eliminate 'a'\n *\n * console.log(cache.get('a')); // undefined\n * console.log(cache.get('b')); // 2\n * console.log(cache.get('c')); // 3\n * console.log(cache.get('d')); // 4\n *\n * // The priority of an element should be updated when it is accessed\n * cache.clear();\n * cache.set('a', 1);\n * cache.set('b', 2);\n * cache.set('c', 3);\n *\n * cache.get('a'); // access 'a'\n * cache.set('d', 4); // This will eliminate 'b'\n *\n * console.log(cache.get('a')); // 1\n * console.log(cache.get('b')); // undefined\n * console.log(cache.get('c')); // 3\n * console.log(cache.get('d')); // 4\n *\n * // Should support updating existing keys\n * cache.clear();\n * cache.set('a', 1);\n * cache.set('a', 10);\n *\n * console.log(cache.get('a')); // 10\n *\n * // Should support deleting specified keys\n * cache.clear();\n * cache.set('a', 1);\n * cache.set('b', 2);\n *\n * console.log(cache.delete('a')); // true\n * console.log(cache.get('a')); // undefined\n * console.log(cache.length); // 1\n *\n * // Should support clearing cache\n * cache.clear();\n * cache.set('a', 1);\n * cache.set('b', 2);\n * cache.clear();\n *\n * console.log(cache.length); // 0\n * console.log(cache.isEmpty); // true\n * @example\n * // finding lyrics by timestamp in Coldplay's \"Fix You\"\n * // Create a DoublyLinkedList to store song lyrics with timestamps\n * const lyricsList = new DoublyLinkedList<{ time: number; text: string }>();\n *\n * // Detailed lyrics with precise timestamps (in milliseconds)\n * const lyrics = [\n * { time: 0, text: \"When you try your best, but you don't succeed\" },\n * { time: 4000, text: 'When you get what you want, but not what you need' },\n * { time: 8000, text: \"When you feel so tired, but you can't sleep\" },\n * { time: 12000, text: 'Stuck in reverse' },\n * { time: 16000, text: 'And the tears come streaming down your face' },\n * { time: 20000, text: \"When you lose something you can't replace\" },\n * { time: 24000, text: 'When you love someone, but it goes to waste' },\n * { time: 28000, text: 'Could it be worse?' },\n * { time: 32000, text: 'Lights will guide you home' },\n * { time: 36000, text: 'And ignite your bones' },\n * { time: 40000, text: 'And I will try to fix you' }\n * ];\n *\n * // Populate the DoublyLinkedList with lyrics\n * lyrics.forEach(lyric => lyricsList.push(lyric));\n *\n * // Test different scenarios of lyric synchronization\n *\n * // 1. Find lyric at exact timestamp\n * const exactTimeLyric = lyricsList.getBackward(lyric => lyric.value.time <= 36000);\n * console.log(exactTimeLyric?.text); // 'And ignite your bones'\n *\n * // 2. Find lyric between timestamps\n * const betweenTimeLyric = lyricsList.getBackward(lyric => lyric.value.time <= 22000);\n * console.log(betweenTimeLyric?.text); // \"When you lose something you can't replace\"\n *\n * // 3. Find first lyric when timestamp is less than first entry\n * const earlyTimeLyric = lyricsList.getBackward(lyric => lyric.value.time <= -1000);\n * console.log(earlyTimeLyric); // undefined\n *\n * // 4. Find last lyric when timestamp is after last entry\n * const lateTimeLyric = lyricsList.getBackward(lyric => lyric.value.time <= 50000);\n * console.log(lateTimeLyric?.text); // 'And I will try to fix you'\n * @example\n * // cpu process schedules\n * class Process {\n * constructor(\n * public id: number,\n * public priority: number\n * ) {}\n *\n * execute(): string {\n * return `Process ${this.id} executed.`;\n * }\n * }\n *\n * class Scheduler {\n * private queue: DoublyLinkedList<Process>;\n *\n * constructor() {\n * this.queue = new DoublyLinkedList<Process>();\n * }\n *\n * addProcess(process: Process): void {\n * // Insert processes into a queue based on priority, keeping priority in descending order\n * let current = this.queue.head;\n * while (current && current.value.priority >= process.priority) {\n * current = current.next;\n * }\n *\n * if (!current) {\n * this.queue.push(process);\n * } else {\n * this.queue.addBefore(current, process);\n * }\n * }\n *\n * executeNext(): string | undefined {\n * // Execute tasks at the head of the queue in order\n * const process = this.queue.shift();\n * return process ? process.execute() : undefined;\n * }\n *\n * listProcesses(): string[] {\n * return this.queue.toArray().map(process => `Process ${process.id} (Priority: ${process.priority})`);\n * }\n *\n * clear(): void {\n * this.queue.clear();\n * }\n * }\n *\n * // should add processes based on priority\n * let scheduler = new Scheduler();\n * scheduler.addProcess(new Process(1, 10));\n * scheduler.addProcess(new Process(2, 20));\n * scheduler.addProcess(new Process(3, 15));\n *\n * console.log(scheduler.listProcesses()); // [\n * // 'Process 2 (Priority: 20)',\n * // 'Process 3 (Priority: 15)',\n * // 'Process 1 (Priority: 10)'\n * // ]\n *\n * // should execute the highest priority process\n * scheduler = new Scheduler();\n * scheduler.addProcess(new Process(1, 10));\n * scheduler.addProcess(new Process(2, 20));\n *\n * console.log(scheduler.executeNext()); // 'Process 2 executed.'\n * console.log(scheduler.listProcesses()); // ['Process 1 (Priority: 10)']\n *\n * // should clear all processes\n * scheduler = new Scheduler();\n * scheduler.addProcess(new Process(1, 10));\n * scheduler.addProcess(new Process(2, 20));\n *\n * scheduler.clear();\n * console.log(scheduler.listProcesses()); // []\n */\nexport class DoublyLinkedList<E = any, R = any> extends LinearLinkedBase<E, R, DoublyLinkedListNode<E>> {\n protected _equals: (a: E, b: E) => boolean = Object.is as unknown as (a: E, b: E) => boolean;\n\n /**\n * Create a DoublyLinkedList and optionally bulk-insert elements.\n * @remarks Time O(N), Space O(N)\n * @param [elements] - Iterable of elements or nodes (or raw records if toElementFn is provided).\n * @param [options] - Options such as maxLen and toElementFn.\n * @returns New DoublyLinkedList instance.\n */\n\n constructor(\n elements: Iterable<E> | Iterable<R> | Iterable<DoublyLinkedListNode<E>> = [],\n options?: DoublyLinkedListOptions<E, R>\n ) {\n super(options);\n this._head = undefined;\n this._tail = undefined;\n this._length = 0;\n\n if (options?.maxLen && Number.isInteger(options.maxLen) && options.maxLen > 0) {\n this._maxLen = options.maxLen;\n }\n\n this.pushMany(elements);\n }\n\n protected _head: DoublyLinkedListNode<E> | undefined;\n\n /**\n * Get the head node.\n * @remarks Time O(1), Space O(1)\n * @returns Head node or undefined.\n */\n\n get head(): DoublyLinkedListNode<E> | undefined {\n return this._head;\n }\n\n protected _tail: DoublyLinkedListNode<E> | undefined;\n\n /**\n * Get the tail node.\n * @remarks Time O(1), Space O(1)\n * @returns Tail node or undefined.\n */\n\n get tail(): DoublyLinkedListNode<E> | undefined {\n return this._tail;\n }\n\n protected _length = 0;\n\n /**\n * Get the number of elements.\n * @remarks Time O(1), Space O(1)\n * @returns Current length.\n */\n\n get length(): number {\n return this._length;\n }\n\n /**\n * Get the first element value.\n * @remarks Time O(1), Space O(1)\n * @returns First element or undefined.\n */\n\n get first(): E | undefined {\n return this.head?.value;\n }\n\n /**\n * Get the last element value.\n * @remarks Time O(1), Space O(1)\n * @returns Last element or undefined.\n */\n\n get last(): E | undefined {\n return this.tail?.value;\n }\n\n /**\n * Create a new list from an array of elements.\n * @remarks Time O(N), Space O(N)\n * @template E\n * @template R\n * @param this - The constructor (subclass) to instantiate.\n * @param data - Array of elements to insert.\n * @returns A new list populated with the array's elements.\n */\n\n static fromArray<E, R = any>(\n this: new (\n elements?: Iterable<E> | Iterable<R> | Iterable<DoublyLinkedListNode<E>>,\n options?: DoublyLinkedListOptions<E, R>\n ) => any,\n data: E[]\n ) {\n return new this(data);\n }\n\n /**\n * Type guard: check whether the input is a DoublyLinkedListNode.\n * @remarks Time O(1), Space O(1)\n * @param elementNodeOrPredicate - Element, node, or predicate.\n * @returns True if the value is a DoublyLinkedListNode.\n */\n\n isNode(\n elementNodeOrPredicate: E | DoublyLinkedListNode<E> | ((node: DoublyLinkedListNode<E>) => boolean)\n ): elementNodeOrPredicate is DoublyLinkedListNode<E> {\n return elementNodeOrPredicate instanceof DoublyLinkedListNode;\n }\n\n /**\n * Append an element/node to the tail.\n * @remarks Time O(1), Space O(1)\n * @param elementOrNode - Element or node to append.\n * @returns True when appended.\n */\n\n push(elementOrNode: E | DoublyLinkedListNode<E>): boolean {\n const newNode = this._ensureNode(elementOrNode);\n if (!this.head) {\n this._head = newNode;\n this._tail = newNode;\n } else {\n newNode.prev = this.tail;\n this.tail!.next = newNode;\n this._tail = newNode;\n }\n this._length++;\n if (this._maxLen > 0 && this.length > this._maxLen) this.shift();\n return true;\n }\n\n /**\n * Remove and return the tail element.\n * @remarks Time O(1), Space O(1)\n * @returns Removed element or undefined.\n */\n\n pop(): E | undefined {\n if (!this.tail) return undefined;\n const removed = this.tail;\n if (this.head === this.tail) {\n this._head = undefined;\n this._tail = undefined;\n } else {\n this._tail = removed.prev;\n this.tail!.next = undefined;\n }\n this._length--;\n return removed.value;\n }\n\n /**\n * Remove and return the head element.\n * @remarks Time O(1), Space O(1)\n * @returns Removed element or undefined.\n */\n\n shift(): E | undefined {\n if (!this.head) return undefined;\n const removed = this.head;\n if (this.head === this.tail) {\n this._head = undefined;\n this._tail = undefined;\n } else {\n this._head = removed.next;\n this.head!.prev = undefined;\n }\n this._length--;\n return removed.value;\n }\n\n /**\n * Prepend an element/node to the head.\n * @remarks Time O(1), Space O(1)\n * @param elementOrNode - Element or node to prepend.\n * @returns True when prepended.\n */\n\n unshift(elementOrNode: E | DoublyLinkedListNode<E>): boolean {\n const newNode = this._ensureNode(elementOrNode);\n if (!this.head) {\n this._head = newNode;\n this._tail = newNode;\n } else {\n newNode.next = this.head;\n this.head!.prev = newNode;\n this._head = newNode;\n }\n this._length++;\n if (this._maxLen > 0 && this._length > this._maxLen) this.pop();\n return true;\n }\n\n /**\n * Append a sequence of elements/nodes.\n * @remarks Time O(N), Space O(1)\n * @param elements - Iterable of elements or nodes (or raw records if toElementFn is provided).\n * @returns Array of per-element success flags.\n */\n\n pushMany(elements: Iterable<E> | Iterable<R> | Iterable<DoublyLinkedListNode<E>>): 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 | DoublyLinkedListNode<E>));\n }\n return ans;\n }\n\n /**\n * Prepend a sequence of elements/nodes.\n * @remarks Time O(N), Space O(1)\n * @param elements - Iterable of elements or nodes (or raw records if toElementFn is provided).\n * @returns Array of per-element success flags.\n */\n\n unshiftMany(elements: Iterable<E> | Iterable<R> | Iterable<DoublyLinkedListNode<E>>): boolean[] {\n const ans: boolean[] = [];\n for (const el of elements) {\n if (this.toElementFn) ans.push(this.unshift(this.toElementFn(el as R)));\n else ans.push(this.unshift(el as E | DoublyLinkedListNode<E>));\n }\n return ans;\n }\n\n /**\n * Get the element at a given index.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index.\n * @returns Element or undefined.\n */\n\n at(index: number): E | undefined {\n if (index < 0 || index >= this._length) return undefined;\n let current = this.head;\n for (let i = 0; i < index; i++) current = current!.next;\n return current!.value;\n }\n\n /**\n * Get the node reference at a given index.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index.\n * @returns Node or undefined.\n */\n\n getNodeAt(index: number): DoublyLinkedListNode<E> | undefined {\n if (index < 0 || index >= this._length) return undefined;\n let current = this.head;\n for (let i = 0; i < index; i++) current = current!.next;\n return current;\n }\n\n /**\n * Find a node by value, reference, or predicate.\n * @remarks Time O(N), Space O(1)\n * @param [elementNodeOrPredicate] - Element, node, or predicate to match.\n * @returns Matching node or undefined.\n */\n\n getNode(\n elementNodeOrPredicate: E | DoublyLinkedListNode<E> | ((node: DoublyLinkedListNode<E>) => boolean) | undefined\n ): DoublyLinkedListNode<E> | undefined {\n if (elementNodeOrPredicate === undefined) return;\n\n if (this.isNode(elementNodeOrPredicate)) {\n const target = elementNodeOrPredicate;\n\n let cur = this.head;\n while (cur) {\n if (cur === target) return target;\n cur = cur.next;\n }\n\n const isMatch = (node: DoublyLinkedListNode<E>) => this._equals(node.value, target.value);\n cur = this.head;\n while (cur) {\n if (isMatch(cur)) return cur;\n cur = cur.next;\n }\n return undefined;\n }\n\n const predicate = this._ensurePredicate(elementNodeOrPredicate);\n let current = this.head;\n while (current) {\n if (predicate(current)) return current;\n current = current.next;\n }\n return undefined;\n }\n\n /**\n * Insert a new element/node at an index, shifting following nodes.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index.\n * @param newElementOrNode - Element or node to insert.\n * @returns True if inserted.\n */\n\n addAt(index: number, newElementOrNode: E | DoublyLinkedListNode<E>): boolean {\n if (index < 0 || index > this._length) return false;\n if (index === 0) return this.unshift(newElementOrNode);\n if (index === this._length) return this.push(newElementOrNode);\n\n const newNode = this._ensureNode(newElementOrNode);\n const prevNode = this.getNodeAt(index - 1)!;\n const nextNode = prevNode.next!;\n newNode.prev = prevNode;\n newNode.next = nextNode;\n prevNode.next = newNode;\n nextNode.prev = newNode;\n this._length++;\n return true;\n }\n\n /**\n * Insert a new element/node before an existing one.\n * @remarks Time O(N), Space O(1)\n * @param existingElementOrNode - Existing element or node.\n * @param newElementOrNode - Element or node to insert.\n * @returns True if inserted.\n */\n\n addBefore(\n existingElementOrNode: E | DoublyLinkedListNode<E>,\n newElementOrNode: E | DoublyLinkedListNode<E>\n ): boolean {\n const existingNode = this.isNode(existingElementOrNode)\n ? existingElementOrNode\n : this.getNode(existingElementOrNode);\n if (!existingNode) return false;\n\n const newNode = this._ensureNode(newElementOrNode);\n newNode.prev = existingNode.prev;\n if (existingNode.prev) existingNode.prev.next = newNode;\n newNode.next = existingNode;\n existingNode.prev = newNode;\n if (existingNode === this.head) this._head = newNode;\n this._length++;\n return true;\n }\n\n /**\n * Insert a new element/node after an existing one.\n * @remarks Time O(N), Space O(1)\n * @param existingElementOrNode - Existing element or node.\n * @param newElementOrNode - Element or node to insert.\n * @returns True if inserted.\n */\n\n addAfter(existingElementOrNode: E | DoublyLinkedListNode<E>, newElementOrNode: E | DoublyLinkedListNode<E>): boolean {\n const existingNode = this.isNode(existingElementOrNode)\n ? existingElementOrNode\n : this.getNode(existingElementOrNode);\n if (!existingNode) return false;\n\n const newNode = this._ensureNode(newElementOrNode);\n newNode.next = existingNode.next;\n if (existingNode.next) existingNode.next.prev = newNode;\n newNode.prev = existingNode;\n existingNode.next = newNode;\n if (existingNode === this.tail) this._tail = newNode;\n this._length++;\n return true;\n }\n\n /**\n * Set the element value at an index.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index.\n * @param value - New value.\n * @returns True if updated.\n */\n\n setAt(index: number, value: E): boolean {\n const node = this.getNodeAt(index);\n if (!node) return false;\n node.value = value;\n return true;\n }\n\n /**\n * Delete the element at an index.\n * @remarks Time O(N), Space O(1)\n * @param index - Zero-based index.\n * @returns Removed element or undefined.\n */\n\n deleteAt(index: number): E | undefined {\n if (index < 0 || index >= this._length) return;\n if (index === 0) return this.shift();\n if (index === this._length - 1) return this.pop();\n\n const removedNode = this.getNodeAt(index)!;\n const prevNode = removedNode.prev!;\n const nextNode = removedNode.next!;\n prevNode.next = nextNode;\n nextNode.prev = prevNode;\n this._length--;\n return removedNode.value;\n }\n\n /**\n * Delete the first match by value/node.\n * @remarks Time O(N), Space O(1)\n * @param [elementOrNode] - Element or node to remove.\n * @returns True if removed.\n */\n\n delete(elementOrNode: E | DoublyLinkedListNode<E> | undefined): boolean {\n const node = this.getNode(elementOrNode);\n if (!node) return false;\n\n if (node === this.head) this.shift();\n else if (node === this.tail) this.pop();\n else {\n const prevNode = node.prev!;\n const nextNode = node.next!;\n prevNode.next = nextNode;\n nextNode.prev = prevNode;\n this._length--;\n }\n return true;\n }\n\n /**\n * Check whether the list 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 * Remove all nodes and reset length.\n * @remarks Time O(N), Space O(1)\n * @returns void\n */\n\n clear(): void {\n this._head = undefined;\n this._tail = undefined;\n this._length = 0;\n }\n\n /**\n * Find the first value matching a predicate scanning forward.\n * @remarks Time O(N), Space O(1)\n * @param elementNodeOrPredicate - Element, node, or predicate to match.\n * @returns Matched value or undefined.\n */\n\n search(\n elementNodeOrPredicate: E | DoublyLinkedListNode<E> | ((node: DoublyLinkedListNode<E>) => boolean)\n ): E | undefined {\n const predicate = this._ensurePredicate(elementNodeOrPredicate);\n let current = this.head;\n while (current) {\n if (predicate(current)) return current.value;\n current = current.next;\n }\n return undefined;\n }\n\n /**\n * Find the first value matching a predicate scanning backward.\n * @remarks Time O(N), Space O(1)\n * @param elementNodeOrPredicate - Element, node, or predicate to match.\n * @returns Matched value or undefined.\n */\n\n getBackward(\n elementNodeOrPredicate: E | DoublyLinkedListNode<E> | ((node: DoublyLinkedListNode<E>) => boolean)\n ): E | undefined {\n const predicate = this._ensurePredicate(elementNodeOrPredicate);\n let current = this.tail;\n while (current) {\n if (predicate(current)) return current.value;\n current = current.prev;\n }\n return undefined;\n }\n\n /**\n * Reverse the list in place.\n * @remarks Time O(N), Space O(1)\n * @returns This list.\n */\n\n reverse(): this {\n let current = this.head;\n [this._head, this._tail] = [this.tail, this.head];\n while (current) {\n const next = current.next;\n [current.prev, current.next] = [current.next, current.prev];\n current = next;\n }\n return this;\n }\n\n /**\n * Set the equality comparator used to compare values.\n * @remarks Time O(1), Space O(1)\n * @param equals - Equality predicate (a, b) → boolean.\n * @returns This list.\n */\n\n setEquality(equals: (a: E, b: E) => boolean): this {\n this._equals = equals;\n return this;\n }\n\n /**\n * Deep clone this list (values are copied by reference).\n * @remarks Time O(N), Space O(N)\n * @returns A new list with the same element sequence.\n */\n\n 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 * Filter values into a new list of the same class.\n * @remarks Time O(N), Space O(N)\n * @param callback - Predicate (value, index, list) → boolean to keep value.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new list with kept values.\n */\n\n filter(callback: ElementCallback<E, R, boolean>, thisArg?: any): this {\n const out = this._createInstance({ toElementFn: this._toElementFn, maxLen: this._maxLen });\n let index = 0;\n for (const v of this) if (callback.call(thisArg, v, index++, this)) out.push(v);\n return out;\n }\n\n /**\n * Map values into a new list of the same class.\n * @remarks Time O(N), Space O(N)\n * @param callback - Mapping function (value, index, list) → newValue.\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new list with mapped values.\n */\n\n mapSame(callback: ElementCallback<E, R, E>, thisArg?: any): this {\n const out = this._createInstance({ toElementFn: this._toElementFn, maxLen: this._maxLen });\n let index = 0;\n for (const v of this) {\n const mv = thisArg === undefined ? callback(v, index++, this) : callback.call(thisArg, v, index++, this);\n out.push(mv);\n }\n return out;\n }\n\n /**\n * Map values into a new list (possibly different element type).\n * @remarks Time O(N), Space O(N)\n * @template EM\n * @template RM\n * @param callback - Mapping function (value, index, list) → newElement.\n * @param [options] - Options for the output list (e.g., maxLen, toElementFn).\n * @param [thisArg] - Value for `this` inside the callback.\n * @returns A new DoublyLinkedList with mapped values.\n */\n\n map<EM, RM>(\n callback: ElementCallback<E, R, EM>,\n options?: DoublyLinkedListOptions<EM, RM>,\n thisArg?: any\n ): DoublyLinkedList<EM, RM> {\n const out = this._createLike<EM, RM>([], { ...(options ?? {}), maxLen: this._maxLen });\n let index = 0;\n for (const v of this) out.push(callback.call(thisArg, v, index++, this));\n return out;\n }\n\n /**\n * (Protected) Create or return a node for the given input (node or raw element).\n * @remarks Time O(1), Space O(1)\n * @param elementOrNode - Element value or node to normalize.\n * @returns A DoublyLinkedListNode for the provided input.\n */\n\n protected _ensureNode(elementOrNode: E | DoublyLinkedListNode<E>) {\n if (this.isNode(elementOrNode)) return elementOrNode;\n return new DoublyLinkedListNode<E>(elementOrNode);\n }\n\n /**\n * (Protected) Normalize input into a predicate over nodes.\n * @remarks Time O(1), Space O(1)\n * @param elementNodeOrPredicate - Element, node, or node predicate.\n * @returns A predicate function taking a node and returning true/false.\n */\n\n protected _ensurePredicate(\n elementNodeOrPredicate: E | DoublyLinkedListNode<E> | ((node: DoublyLinkedListNode<E>) => boolean)\n ): (node: DoublyLinkedListNode<E>) => boolean {\n if (this.isNode(elementNodeOrPredicate)) {\n const target = elementNodeOrPredicate;\n return (node: DoublyLinkedListNode<E>) => node === target;\n }\n if (typeof elementNodeOrPredicate === 'function') {\n return elementNodeOrPredicate as (node: DoublyLinkedListNode<E>) => boolean;\n }\n const value = elementNodeOrPredicate as E;\n return (node: DoublyLinkedListNode<E>) => this._equals(node.value, value);\n }\n\n /**\n * (Protected) Get the previous node of a given node.\n * @remarks Time O(1), Space O(1)\n * @param node - A node in the list.\n * @returns Previous node or undefined.\n */\n\n protected _getPrevNode(node: DoublyLinkedListNode<E>): DoublyLinkedListNode<E> | undefined {\n return node.prev;\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 list instance.\n */\n\n protected override _createInstance(options?: LinearBaseOptions<E, R>): this {\n const Ctor = this.constructor as new (\n elements?: Iterable<E> | Iterable<R> | Iterable<DoublyLinkedListNode<E>>,\n options?: DoublyLinkedListOptions<E, R>\n ) => this;\n return new Ctor([], options as DoublyLinkedListOptions<E, R> | undefined);\n }\n\n /**\n * (Protected) Create a like-kind instance 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 list.\n * @param [options] - Options forwarded to the constructor.\n * @returns A like-kind DoublyLinkedList instance.\n */\n\n protected _createLike<EM = E, RM = R>(\n elements: Iterable<EM> | Iterable<RM> | Iterable<DoublyLinkedListNode<EM>> = [],\n options?: DoublyLinkedListOptions<EM, RM>\n ): DoublyLinkedList<EM, RM> {\n const Ctor = this.constructor as new (\n elements?: Iterable<EM> | Iterable<RM> | Iterable<DoublyLinkedListNode<EM>>,\n options?: DoublyLinkedListOptions<EM, RM>\n ) => DoublyLinkedList<EM, RM>;\n return new Ctor(elements, options);\n }\n\n protected *_getIterator(): IterableIterator<E> {\n let current = this.head;\n while (current) {\n yield current.value;\n current = current.next;\n }\n }\n\n protected *_getReverseIterator(): IterableIterator<E> {\n let current = this.tail;\n while (current) {\n yield current.value;\n current = current.prev;\n }\n }\n\n protected *_getNodeIterator(): IterableIterator<DoublyLinkedListNode<E>> {\n let current = this.head;\n while (current) {\n yield current;\n current = current.next;\n }\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 */\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 { 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":"ilBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,kBAAAE,EAAA,qBAAAC,EAAA,yBAAAC,EAAA,UAAAC,ICaO,IAAeC,EAAf,KAAgE,CAU3D,YAAYC,EAA4C,CAclEC,EAAA,KAAU,gBAbR,GAAID,EAAS,CACX,GAAM,CAAE,YAAAE,CAAY,EAAIF,EACxB,GAAI,OAAOE,GAAgB,WAAY,KAAK,aAAeA,UAClDA,EAAa,MAAM,IAAI,UAAU,qCAAqC,CACjF,CACF,CAiBA,IAAI,aAAkD,CACpD,OAAO,KAAK,YACd,CAWA,EAAE,OAAO,QAAQ,KAAKC,EAAsC,CAC1D,MAAO,KAAK,aAAa,GAAGA,CAAI,CAClC,CASA,CAAC,QAA8B,CAC7B,QAAWC,KAAQ,KAAM,MAAMA,CACjC,CAaA,MAAMC,EAA2CC,EAA4B,CAC3E,IAAIC,EAAQ,EACZ,QAAWH,KAAQ,KACjB,GAAIE,IAAY,QACd,GAAI,CAACD,EAAUD,EAAMG,IAAS,IAAI,EAAG,MAA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EAAMC,EAAM,MAAM,IAAI,WAAW,wCAAwC,CAC/E,CAGA,UAAUI,EAAQC,EAA6C,CAC7D,IAAMC,EAAW,KAAK,WAAaD,EAAWD,EAAK,KAAK,GAAG,GAAK,EAAIC,EAAWD,EAAK,KAAK,GAAG,EAAI,EAC1FG,EAAY,KAAK,YAAcF,EAAWD,EAAK,KAAK,IAAI,GAAK,EAAIC,EAAWD,EAAK,KAAK,IAAI,EAAI,EACpG,OAAOE,GAAYC,CACrB,CACF","names":["src_exports","__export","DFSOperation","DoublyLinkedList","DoublyLinkedListNode","Range","IterableElementBase","options","__publicField","toElementFn","args","item","predicate","thisArg","index","callbackfn","element","ele","initialValue","iter","acc","first","value","LinkedListNode","value","__publicField","LinearBase","_LinearBase","IterableElementBase","options","maxLen","searchElement","fromIndex","i","predicate","thisArg","item","items","newList","compareFn","arr","start","deleteCount","removedList","removed","separator","array","callbackfn","initialValue","accumulator","end","LinearLinkedBase","iterator","current","index","c","currentIndex","currentNode","previousNode","node","nextNode","DoublyLinkedListNode","LinkedListNode","value","__publicField","DoublyLinkedList","LinearLinkedBase","elements","options","_a","data","elementNodeOrPredicate","elementOrNode","newNode","removed","ans","el","index","current","i","target","cur","isMatch","node","predicate","newElementOrNode","prevNode","nextNode","existingElementOrNode","existingNode","removedNode","next","equals","out","v","callback","thisArg","mv","Ctor","isPrimitiveComparable","value","valueType","tryObjectToPrimitive","obj","valueOfResult","stringResult","isComparable","isForceObjectComparable","comparableValue","DFSOperation","Range","low","high","includeLow","includeHigh","isComparable","key","comparator","lowCheck","highCheck"]}