stack-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 +552 -0
  2. package/dist/cjs/index.cjs.map +1 -0
  3. package/dist/esm/index.mjs +548 -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/stack-typed.js +563 -0
  87. package/dist/umd/stack-typed.js.map +1 -0
  88. package/dist/umd/stack-typed.min.js +9 -0
  89. package/dist/umd/stack-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
@@ -1,1111 +0,0 @@
1
- "use strict";
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
- Object.defineProperty(exports, "__esModule", { value: true });
10
- exports.DoublyLinkedList = exports.DoublyLinkedListNode = void 0;
11
- const linear_base_1 = require("../base/linear-base");
12
- /**
13
- * Node of a doubly linked list; stores value and prev/next links.
14
- * @remarks Time O(1), Space O(1)
15
- * @template E
16
- */
17
- class DoublyLinkedListNode extends linear_base_1.LinkedListNode {
18
- /**
19
- * Create a node.
20
- * @remarks Time O(1), Space O(1)
21
- * @param value - Element value to store.
22
- * @returns New node instance.
23
- */
24
- constructor(value) {
25
- super(value);
26
- this._value = value;
27
- this._next = undefined;
28
- this._prev = undefined;
29
- }
30
- /**
31
- * Get the next node link.
32
- * @remarks Time O(1), Space O(1)
33
- * @returns Next node or undefined.
34
- */
35
- get next() {
36
- return this._next;
37
- }
38
- /**
39
- * Set the next node link.
40
- * @remarks Time O(1), Space O(1)
41
- * @param value - Next node or undefined.
42
- * @returns void
43
- */
44
- set next(value) {
45
- this._next = value;
46
- }
47
- /**
48
- * Get the previous node link.
49
- * @remarks Time O(1), Space O(1)
50
- * @returns Previous node or undefined.
51
- */
52
- get prev() {
53
- return this._prev;
54
- }
55
- /**
56
- * Set the previous node link.
57
- * @remarks Time O(1), Space O(1)
58
- * @param value - Previous node or undefined.
59
- * @returns void
60
- */
61
- set prev(value) {
62
- this._prev = value;
63
- }
64
- }
65
- exports.DoublyLinkedListNode = DoublyLinkedListNode;
66
- /**
67
- * Doubly linked list with O(1) push/pop/unshift/shift and linear scans.
68
- * @remarks Time O(1), Space O(1)
69
- * @template E
70
- * @template R
71
- * 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.
72
- * 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.
73
- * 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.
74
- * 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.
75
- * 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).
76
- * @example
77
- * // text editor operation history
78
- * const actions = [
79
- * { type: 'insert', content: 'first line of text' },
80
- * { type: 'insert', content: 'second line of text' },
81
- * { type: 'delete', content: 'delete the first line' }
82
- * ];
83
- * const editorHistory = new DoublyLinkedList<{ type: string; content: string }>(actions);
84
- *
85
- * console.log(editorHistory.last?.type); // 'delete'
86
- * console.log(editorHistory.pop()?.content); // 'delete the first line'
87
- * console.log(editorHistory.last?.type); // 'insert'
88
- * @example
89
- * // Browser history
90
- * const browserHistory = new DoublyLinkedList<string>();
91
- *
92
- * browserHistory.push('home page');
93
- * browserHistory.push('search page');
94
- * browserHistory.push('details page');
95
- *
96
- * console.log(browserHistory.last); // 'details page'
97
- * console.log(browserHistory.pop()); // 'details page'
98
- * console.log(browserHistory.last); // 'search page'
99
- * @example
100
- * // Use DoublyLinkedList to implement music player
101
- * // Define the Song interface
102
- * interface Song {
103
- * title: string;
104
- * artist: string;
105
- * duration: number; // duration in seconds
106
- * }
107
- *
108
- * class Player {
109
- * private playlist: DoublyLinkedList<Song>;
110
- * private currentSong: ReturnType<typeof this.playlist.getNodeAt> | undefined;
111
- *
112
- * constructor(songs: Song[]) {
113
- * this.playlist = new DoublyLinkedList<Song>();
114
- * songs.forEach(song => this.playlist.push(song));
115
- * this.currentSong = this.playlist.head;
116
- * }
117
- *
118
- * // Play the next song in the playlist
119
- * playNext(): Song | undefined {
120
- * if (!this.currentSong?.next) {
121
- * this.currentSong = this.playlist.head; // Loop to the first song
122
- * } else {
123
- * this.currentSong = this.currentSong.next;
124
- * }
125
- * return this.currentSong?.value;
126
- * }
127
- *
128
- * // Play the previous song in the playlist
129
- * playPrevious(): Song | undefined {
130
- * if (!this.currentSong?.prev) {
131
- * this.currentSong = this.playlist.tail; // Loop to the last song
132
- * } else {
133
- * this.currentSong = this.currentSong.prev;
134
- * }
135
- * return this.currentSong?.value;
136
- * }
137
- *
138
- * // Get the current song
139
- * getCurrentSong(): Song | undefined {
140
- * return this.currentSong?.value;
141
- * }
142
- *
143
- * // Loop through the playlist twice
144
- * loopThroughPlaylist(): Song[] {
145
- * const playedSongs: Song[] = [];
146
- * const initialNode = this.currentSong;
147
- *
148
- * // Loop through the playlist twice
149
- * for (let i = 0; i < this.playlist.length * 2; i++) {
150
- * playedSongs.push(this.currentSong!.value);
151
- * this.currentSong = this.currentSong!.next || this.playlist.head; // Loop back to the start if needed
152
- * }
153
- *
154
- * // Reset the current song to the initial song
155
- * this.currentSong = initialNode;
156
- * return playedSongs;
157
- * }
158
- * }
159
- *
160
- * const songs = [
161
- * { title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 },
162
- * { title: 'Hotel California', artist: 'Eagles', duration: 391 },
163
- * { title: 'Shape of You', artist: 'Ed Sheeran', duration: 233 },
164
- * { title: 'Billie Jean', artist: 'Michael Jackson', duration: 294 }
165
- * ];
166
- * let player = new Player(songs);
167
- * // should play the next song
168
- * player = new Player(songs);
169
- * const firstSong = player.getCurrentSong();
170
- * const nextSong = player.playNext();
171
- *
172
- * // Expect the next song to be "Hotel California by Eagles"
173
- * console.log(nextSong); // { title: 'Hotel California', artist: 'Eagles', duration: 391 }
174
- * console.log(firstSong); // { title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 }
175
- *
176
- * // should play the previous song
177
- * player = new Player(songs);
178
- * player.playNext(); // Move to the second song
179
- * const currentSong = player.getCurrentSong();
180
- * const previousSong = player.playPrevious();
181
- *
182
- * // Expect the previous song to be "Bohemian Rhapsody by Queen"
183
- * console.log(previousSong); // { title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 }
184
- * console.log(currentSong); // { title: 'Hotel California', artist: 'Eagles', duration: 391 }
185
- *
186
- * // should loop to the first song when playing next from the last song
187
- * player = new Player(songs);
188
- * player.playNext(); // Move to the second song
189
- * player.playNext(); // Move to the third song
190
- * player.playNext(); // Move to the fourth song
191
- *
192
- * const nextSongToFirst = player.playNext(); // Should loop to the first song
193
- *
194
- * // Expect the next song to be "Bohemian Rhapsody by Queen"
195
- * console.log(nextSongToFirst); // { title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 }
196
- *
197
- * // should loop to the last song when playing previous from the first song
198
- * player = new Player(songs);
199
- * player.playNext(); // Move to the first song
200
- * player.playNext(); // Move to the second song
201
- * player.playNext(); // Move to the third song
202
- * player.playNext(); // Move to the fourth song
203
- *
204
- * const previousToLast = player.playPrevious(); // Should loop to the last song
205
- *
206
- * // Expect the previous song to be "Billie Jean by Michael Jackson"
207
- * console.log(previousToLast); // { title: 'Billie Jean', artist: 'Michael Jackson', duration: 294 }
208
- *
209
- * // should loop through the entire playlist
210
- * player = new Player(songs);
211
- * const playedSongs = player.loopThroughPlaylist();
212
- *
213
- * // The expected order of songs for two loops
214
- * console.log(playedSongs); // [
215
- * // { title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 },
216
- * // { title: 'Hotel California', artist: 'Eagles', duration: 391 },
217
- * // { title: 'Shape of You', artist: 'Ed Sheeran', duration: 233 },
218
- * // { title: 'Billie Jean', artist: 'Michael Jackson', duration: 294 },
219
- * // { title: 'Bohemian Rhapsody', artist: 'Queen', duration: 354 },
220
- * // { title: 'Hotel California', artist: 'Eagles', duration: 391 },
221
- * // { title: 'Shape of You', artist: 'Ed Sheeran', duration: 233 },
222
- * // { title: 'Billie Jean', artist: 'Michael Jackson', duration: 294 }
223
- * // ]
224
- * @example
225
- * // Use DoublyLinkedList to implement LRU cache
226
- * interface CacheEntry<K, V> {
227
- * key: K;
228
- * value: V;
229
- * }
230
- *
231
- * class LRUCache<K = string, V = any> {
232
- * private readonly capacity: number;
233
- * private list: DoublyLinkedList<CacheEntry<K, V>>;
234
- * private map: Map<K, DoublyLinkedListNode<CacheEntry<K, V>>>;
235
- *
236
- * constructor(capacity: number) {
237
- * if (capacity <= 0) {
238
- * throw new Error('lru cache capacity must be greater than 0');
239
- * }
240
- * this.capacity = capacity;
241
- * this.list = new DoublyLinkedList<CacheEntry<K, V>>();
242
- * this.map = new Map<K, DoublyLinkedListNode<CacheEntry<K, V>>>();
243
- * }
244
- *
245
- * // Get the current cache length
246
- * get length(): number {
247
- * return this.list.length;
248
- * }
249
- *
250
- * // Check if it is empty
251
- * get isEmpty(): boolean {
252
- * return this.list.isEmpty();
253
- * }
254
- *
255
- * // Get cached value
256
- * get(key: K): V | undefined {
257
- * const node = this.map.get(key);
258
- *
259
- * if (!node) return undefined;
260
- *
261
- * // Move the visited node to the head of the linked list (most recently used)
262
- * this.moveToFront(node);
263
- *
264
- * return node.value.value;
265
- * }
266
- *
267
- * // Set cache value
268
- * set(key: K, value: V): void {
269
- * // Check if it already exists
270
- * const node = this.map.get(key);
271
- *
272
- * if (node) {
273
- * // Update value and move to head
274
- * node.value.value = value;
275
- * this.moveToFront(node);
276
- * return;
277
- * }
278
- *
279
- * // Check capacity
280
- * if (this.list.length >= this.capacity) {
281
- * // Delete the least recently used element (the tail of the linked list)
282
- * const removedNode = this.list.tail;
283
- * if (removedNode) {
284
- * this.map.delete(removedNode.value.key);
285
- * this.list.pop();
286
- * }
287
- * }
288
- *
289
- * // Create new node and add to head
290
- * const newEntry: CacheEntry<K, V> = { key, value };
291
- * this.list.unshift(newEntry);
292
- *
293
- * // Save node reference in map
294
- * const newNode = this.list.head;
295
- * if (newNode) {
296
- * this.map.set(key, newNode);
297
- * }
298
- * }
299
- *
300
- * // Delete specific key
301
- * delete(key: K): boolean {
302
- * const node = this.map.get(key);
303
- * if (!node) return false;
304
- *
305
- * // Remove from linked list
306
- * this.list.delete(node);
307
- * // Remove from map
308
- * this.map.delete(key);
309
- *
310
- * return true;
311
- * }
312
- *
313
- * // Clear cache
314
- * clear(): void {
315
- * this.list.clear();
316
- * this.map.clear();
317
- * }
318
- *
319
- * // Move the node to the head of the linked list
320
- * private moveToFront(node: DoublyLinkedListNode<CacheEntry<K, V>>): void {
321
- * this.list.delete(node);
322
- * this.list.unshift(node.value);
323
- * }
324
- * }
325
- *
326
- * // should set and get values correctly
327
- * const cache = new LRUCache<string, number>(3);
328
- * cache.set('a', 1);
329
- * cache.set('b', 2);
330
- * cache.set('c', 3);
331
- *
332
- * console.log(cache.get('a')); // 1
333
- * console.log(cache.get('b')); // 2
334
- * console.log(cache.get('c')); // 3
335
- *
336
- * // The least recently used element should be evicted when capacity is exceeded
337
- * cache.clear();
338
- * cache.set('a', 1);
339
- * cache.set('b', 2);
340
- * cache.set('c', 3);
341
- * cache.set('d', 4); // This will eliminate 'a'
342
- *
343
- * console.log(cache.get('a')); // undefined
344
- * console.log(cache.get('b')); // 2
345
- * console.log(cache.get('c')); // 3
346
- * console.log(cache.get('d')); // 4
347
- *
348
- * // The priority of an element should be updated when it is accessed
349
- * cache.clear();
350
- * cache.set('a', 1);
351
- * cache.set('b', 2);
352
- * cache.set('c', 3);
353
- *
354
- * cache.get('a'); // access 'a'
355
- * cache.set('d', 4); // This will eliminate 'b'
356
- *
357
- * console.log(cache.get('a')); // 1
358
- * console.log(cache.get('b')); // undefined
359
- * console.log(cache.get('c')); // 3
360
- * console.log(cache.get('d')); // 4
361
- *
362
- * // Should support updating existing keys
363
- * cache.clear();
364
- * cache.set('a', 1);
365
- * cache.set('a', 10);
366
- *
367
- * console.log(cache.get('a')); // 10
368
- *
369
- * // Should support deleting specified keys
370
- * cache.clear();
371
- * cache.set('a', 1);
372
- * cache.set('b', 2);
373
- *
374
- * console.log(cache.delete('a')); // true
375
- * console.log(cache.get('a')); // undefined
376
- * console.log(cache.length); // 1
377
- *
378
- * // Should support clearing cache
379
- * cache.clear();
380
- * cache.set('a', 1);
381
- * cache.set('b', 2);
382
- * cache.clear();
383
- *
384
- * console.log(cache.length); // 0
385
- * console.log(cache.isEmpty); // true
386
- * @example
387
- * // finding lyrics by timestamp in Coldplay's "Fix You"
388
- * // Create a DoublyLinkedList to store song lyrics with timestamps
389
- * const lyricsList = new DoublyLinkedList<{ time: number; text: string }>();
390
- *
391
- * // Detailed lyrics with precise timestamps (in milliseconds)
392
- * const lyrics = [
393
- * { time: 0, text: "When you try your best, but you don't succeed" },
394
- * { time: 4000, text: 'When you get what you want, but not what you need' },
395
- * { time: 8000, text: "When you feel so tired, but you can't sleep" },
396
- * { time: 12000, text: 'Stuck in reverse' },
397
- * { time: 16000, text: 'And the tears come streaming down your face' },
398
- * { time: 20000, text: "When you lose something you can't replace" },
399
- * { time: 24000, text: 'When you love someone, but it goes to waste' },
400
- * { time: 28000, text: 'Could it be worse?' },
401
- * { time: 32000, text: 'Lights will guide you home' },
402
- * { time: 36000, text: 'And ignite your bones' },
403
- * { time: 40000, text: 'And I will try to fix you' }
404
- * ];
405
- *
406
- * // Populate the DoublyLinkedList with lyrics
407
- * lyrics.forEach(lyric => lyricsList.push(lyric));
408
- *
409
- * // Test different scenarios of lyric synchronization
410
- *
411
- * // 1. Find lyric at exact timestamp
412
- * const exactTimeLyric = lyricsList.getBackward(lyric => lyric.value.time <= 36000);
413
- * console.log(exactTimeLyric?.text); // 'And ignite your bones'
414
- *
415
- * // 2. Find lyric between timestamps
416
- * const betweenTimeLyric = lyricsList.getBackward(lyric => lyric.value.time <= 22000);
417
- * console.log(betweenTimeLyric?.text); // "When you lose something you can't replace"
418
- *
419
- * // 3. Find first lyric when timestamp is less than first entry
420
- * const earlyTimeLyric = lyricsList.getBackward(lyric => lyric.value.time <= -1000);
421
- * console.log(earlyTimeLyric); // undefined
422
- *
423
- * // 4. Find last lyric when timestamp is after last entry
424
- * const lateTimeLyric = lyricsList.getBackward(lyric => lyric.value.time <= 50000);
425
- * console.log(lateTimeLyric?.text); // 'And I will try to fix you'
426
- * @example
427
- * // cpu process schedules
428
- * class Process {
429
- * constructor(
430
- * public id: number,
431
- * public priority: number
432
- * ) {}
433
- *
434
- * execute(): string {
435
- * return `Process ${this.id} executed.`;
436
- * }
437
- * }
438
- *
439
- * class Scheduler {
440
- * private queue: DoublyLinkedList<Process>;
441
- *
442
- * constructor() {
443
- * this.queue = new DoublyLinkedList<Process>();
444
- * }
445
- *
446
- * addProcess(process: Process): void {
447
- * // Insert processes into a queue based on priority, keeping priority in descending order
448
- * let current = this.queue.head;
449
- * while (current && current.value.priority >= process.priority) {
450
- * current = current.next;
451
- * }
452
- *
453
- * if (!current) {
454
- * this.queue.push(process);
455
- * } else {
456
- * this.queue.addBefore(current, process);
457
- * }
458
- * }
459
- *
460
- * executeNext(): string | undefined {
461
- * // Execute tasks at the head of the queue in order
462
- * const process = this.queue.shift();
463
- * return process ? process.execute() : undefined;
464
- * }
465
- *
466
- * listProcesses(): string[] {
467
- * return this.queue.toArray().map(process => `Process ${process.id} (Priority: ${process.priority})`);
468
- * }
469
- *
470
- * clear(): void {
471
- * this.queue.clear();
472
- * }
473
- * }
474
- *
475
- * // should add processes based on priority
476
- * let scheduler = new Scheduler();
477
- * scheduler.addProcess(new Process(1, 10));
478
- * scheduler.addProcess(new Process(2, 20));
479
- * scheduler.addProcess(new Process(3, 15));
480
- *
481
- * console.log(scheduler.listProcesses()); // [
482
- * // 'Process 2 (Priority: 20)',
483
- * // 'Process 3 (Priority: 15)',
484
- * // 'Process 1 (Priority: 10)'
485
- * // ]
486
- *
487
- * // should execute the highest priority process
488
- * scheduler = new Scheduler();
489
- * scheduler.addProcess(new Process(1, 10));
490
- * scheduler.addProcess(new Process(2, 20));
491
- *
492
- * console.log(scheduler.executeNext()); // 'Process 2 executed.'
493
- * console.log(scheduler.listProcesses()); // ['Process 1 (Priority: 10)']
494
- *
495
- * // should clear all processes
496
- * scheduler = new Scheduler();
497
- * scheduler.addProcess(new Process(1, 10));
498
- * scheduler.addProcess(new Process(2, 20));
499
- *
500
- * scheduler.clear();
501
- * console.log(scheduler.listProcesses()); // []
502
- */
503
- class DoublyLinkedList extends linear_base_1.LinearLinkedBase {
504
- /**
505
- * Create a DoublyLinkedList and optionally bulk-insert elements.
506
- * @remarks Time O(N), Space O(N)
507
- * @param [elements] - Iterable of elements or nodes (or raw records if toElementFn is provided).
508
- * @param [options] - Options such as maxLen and toElementFn.
509
- * @returns New DoublyLinkedList instance.
510
- */
511
- constructor(elements = [], options) {
512
- super(options);
513
- this._equals = Object.is;
514
- this._length = 0;
515
- this._head = undefined;
516
- this._tail = undefined;
517
- this._length = 0;
518
- if ((options === null || options === void 0 ? void 0 : options.maxLen) && Number.isInteger(options.maxLen) && options.maxLen > 0) {
519
- this._maxLen = options.maxLen;
520
- }
521
- this.pushMany(elements);
522
- }
523
- /**
524
- * Get the head node.
525
- * @remarks Time O(1), Space O(1)
526
- * @returns Head node or undefined.
527
- */
528
- get head() {
529
- return this._head;
530
- }
531
- /**
532
- * Get the tail node.
533
- * @remarks Time O(1), Space O(1)
534
- * @returns Tail node or undefined.
535
- */
536
- get tail() {
537
- return this._tail;
538
- }
539
- /**
540
- * Get the number of elements.
541
- * @remarks Time O(1), Space O(1)
542
- * @returns Current length.
543
- */
544
- get length() {
545
- return this._length;
546
- }
547
- /**
548
- * Get the first element value.
549
- * @remarks Time O(1), Space O(1)
550
- * @returns First element or undefined.
551
- */
552
- get first() {
553
- var _a;
554
- return (_a = this.head) === null || _a === void 0 ? void 0 : _a.value;
555
- }
556
- /**
557
- * Get the last element value.
558
- * @remarks Time O(1), Space O(1)
559
- * @returns Last element or undefined.
560
- */
561
- get last() {
562
- var _a;
563
- return (_a = this.tail) === null || _a === void 0 ? void 0 : _a.value;
564
- }
565
- /**
566
- * Create a new list from an array of elements.
567
- * @remarks Time O(N), Space O(N)
568
- * @template E
569
- * @template R
570
- * @param this - The constructor (subclass) to instantiate.
571
- * @param data - Array of elements to insert.
572
- * @returns A new list populated with the array's elements.
573
- */
574
- static fromArray(data) {
575
- return new this(data);
576
- }
577
- /**
578
- * Type guard: check whether the input is a DoublyLinkedListNode.
579
- * @remarks Time O(1), Space O(1)
580
- * @param elementNodeOrPredicate - Element, node, or predicate.
581
- * @returns True if the value is a DoublyLinkedListNode.
582
- */
583
- isNode(elementNodeOrPredicate) {
584
- return elementNodeOrPredicate instanceof DoublyLinkedListNode;
585
- }
586
- /**
587
- * Append an element/node to the tail.
588
- * @remarks Time O(1), Space O(1)
589
- * @param elementOrNode - Element or node to append.
590
- * @returns True when appended.
591
- */
592
- push(elementOrNode) {
593
- const newNode = this._ensureNode(elementOrNode);
594
- if (!this.head) {
595
- this._head = newNode;
596
- this._tail = newNode;
597
- }
598
- else {
599
- newNode.prev = this.tail;
600
- this.tail.next = newNode;
601
- this._tail = newNode;
602
- }
603
- this._length++;
604
- if (this._maxLen > 0 && this.length > this._maxLen)
605
- this.shift();
606
- return true;
607
- }
608
- /**
609
- * Remove and return the tail element.
610
- * @remarks Time O(1), Space O(1)
611
- * @returns Removed element or undefined.
612
- */
613
- pop() {
614
- if (!this.tail)
615
- return undefined;
616
- const removed = this.tail;
617
- if (this.head === this.tail) {
618
- this._head = undefined;
619
- this._tail = undefined;
620
- }
621
- else {
622
- this._tail = removed.prev;
623
- this.tail.next = undefined;
624
- }
625
- this._length--;
626
- return removed.value;
627
- }
628
- /**
629
- * Remove and return the head element.
630
- * @remarks Time O(1), Space O(1)
631
- * @returns Removed element or undefined.
632
- */
633
- shift() {
634
- if (!this.head)
635
- return undefined;
636
- const removed = this.head;
637
- if (this.head === this.tail) {
638
- this._head = undefined;
639
- this._tail = undefined;
640
- }
641
- else {
642
- this._head = removed.next;
643
- this.head.prev = undefined;
644
- }
645
- this._length--;
646
- return removed.value;
647
- }
648
- /**
649
- * Prepend an element/node to the head.
650
- * @remarks Time O(1), Space O(1)
651
- * @param elementOrNode - Element or node to prepend.
652
- * @returns True when prepended.
653
- */
654
- unshift(elementOrNode) {
655
- const newNode = this._ensureNode(elementOrNode);
656
- if (!this.head) {
657
- this._head = newNode;
658
- this._tail = newNode;
659
- }
660
- else {
661
- newNode.next = this.head;
662
- this.head.prev = newNode;
663
- this._head = newNode;
664
- }
665
- this._length++;
666
- if (this._maxLen > 0 && this._length > this._maxLen)
667
- this.pop();
668
- return true;
669
- }
670
- /**
671
- * Append a sequence of elements/nodes.
672
- * @remarks Time O(N), Space O(1)
673
- * @param elements - Iterable of elements or nodes (or raw records if toElementFn is provided).
674
- * @returns Array of per-element success flags.
675
- */
676
- pushMany(elements) {
677
- const ans = [];
678
- for (const el of elements) {
679
- if (this.toElementFn)
680
- ans.push(this.push(this.toElementFn(el)));
681
- else
682
- ans.push(this.push(el));
683
- }
684
- return ans;
685
- }
686
- /**
687
- * Prepend a sequence of elements/nodes.
688
- * @remarks Time O(N), Space O(1)
689
- * @param elements - Iterable of elements or nodes (or raw records if toElementFn is provided).
690
- * @returns Array of per-element success flags.
691
- */
692
- unshiftMany(elements) {
693
- const ans = [];
694
- for (const el of elements) {
695
- if (this.toElementFn)
696
- ans.push(this.unshift(this.toElementFn(el)));
697
- else
698
- ans.push(this.unshift(el));
699
- }
700
- return ans;
701
- }
702
- /**
703
- * Get the element at a given index.
704
- * @remarks Time O(N), Space O(1)
705
- * @param index - Zero-based index.
706
- * @returns Element or undefined.
707
- */
708
- at(index) {
709
- if (index < 0 || index >= this._length)
710
- return undefined;
711
- let current = this.head;
712
- for (let i = 0; i < index; i++)
713
- current = current.next;
714
- return current.value;
715
- }
716
- /**
717
- * Get the node reference at a given index.
718
- * @remarks Time O(N), Space O(1)
719
- * @param index - Zero-based index.
720
- * @returns Node or undefined.
721
- */
722
- getNodeAt(index) {
723
- if (index < 0 || index >= this._length)
724
- return undefined;
725
- let current = this.head;
726
- for (let i = 0; i < index; i++)
727
- current = current.next;
728
- return current;
729
- }
730
- /**
731
- * Find a node by value, reference, or predicate.
732
- * @remarks Time O(N), Space O(1)
733
- * @param [elementNodeOrPredicate] - Element, node, or predicate to match.
734
- * @returns Matching node or undefined.
735
- */
736
- getNode(elementNodeOrPredicate) {
737
- if (elementNodeOrPredicate === undefined)
738
- return;
739
- if (this.isNode(elementNodeOrPredicate)) {
740
- const target = elementNodeOrPredicate;
741
- let cur = this.head;
742
- while (cur) {
743
- if (cur === target)
744
- return target;
745
- cur = cur.next;
746
- }
747
- const isMatch = (node) => this._equals(node.value, target.value);
748
- cur = this.head;
749
- while (cur) {
750
- if (isMatch(cur))
751
- return cur;
752
- cur = cur.next;
753
- }
754
- return undefined;
755
- }
756
- const predicate = this._ensurePredicate(elementNodeOrPredicate);
757
- let current = this.head;
758
- while (current) {
759
- if (predicate(current))
760
- return current;
761
- current = current.next;
762
- }
763
- return undefined;
764
- }
765
- /**
766
- * Insert a new element/node at an index, shifting following nodes.
767
- * @remarks Time O(N), Space O(1)
768
- * @param index - Zero-based index.
769
- * @param newElementOrNode - Element or node to insert.
770
- * @returns True if inserted.
771
- */
772
- addAt(index, newElementOrNode) {
773
- if (index < 0 || index > this._length)
774
- return false;
775
- if (index === 0)
776
- return this.unshift(newElementOrNode);
777
- if (index === this._length)
778
- return this.push(newElementOrNode);
779
- const newNode = this._ensureNode(newElementOrNode);
780
- const prevNode = this.getNodeAt(index - 1);
781
- const nextNode = prevNode.next;
782
- newNode.prev = prevNode;
783
- newNode.next = nextNode;
784
- prevNode.next = newNode;
785
- nextNode.prev = newNode;
786
- this._length++;
787
- return true;
788
- }
789
- /**
790
- * Insert a new element/node before an existing one.
791
- * @remarks Time O(N), Space O(1)
792
- * @param existingElementOrNode - Existing element or node.
793
- * @param newElementOrNode - Element or node to insert.
794
- * @returns True if inserted.
795
- */
796
- addBefore(existingElementOrNode, newElementOrNode) {
797
- const existingNode = this.isNode(existingElementOrNode)
798
- ? existingElementOrNode
799
- : this.getNode(existingElementOrNode);
800
- if (!existingNode)
801
- return false;
802
- const newNode = this._ensureNode(newElementOrNode);
803
- newNode.prev = existingNode.prev;
804
- if (existingNode.prev)
805
- existingNode.prev.next = newNode;
806
- newNode.next = existingNode;
807
- existingNode.prev = newNode;
808
- if (existingNode === this.head)
809
- this._head = newNode;
810
- this._length++;
811
- return true;
812
- }
813
- /**
814
- * Insert a new element/node after an existing one.
815
- * @remarks Time O(N), Space O(1)
816
- * @param existingElementOrNode - Existing element or node.
817
- * @param newElementOrNode - Element or node to insert.
818
- * @returns True if inserted.
819
- */
820
- addAfter(existingElementOrNode, newElementOrNode) {
821
- const existingNode = this.isNode(existingElementOrNode)
822
- ? existingElementOrNode
823
- : this.getNode(existingElementOrNode);
824
- if (!existingNode)
825
- return false;
826
- const newNode = this._ensureNode(newElementOrNode);
827
- newNode.next = existingNode.next;
828
- if (existingNode.next)
829
- existingNode.next.prev = newNode;
830
- newNode.prev = existingNode;
831
- existingNode.next = newNode;
832
- if (existingNode === this.tail)
833
- this._tail = newNode;
834
- this._length++;
835
- return true;
836
- }
837
- /**
838
- * Set the element value at an index.
839
- * @remarks Time O(N), Space O(1)
840
- * @param index - Zero-based index.
841
- * @param value - New value.
842
- * @returns True if updated.
843
- */
844
- setAt(index, value) {
845
- const node = this.getNodeAt(index);
846
- if (!node)
847
- return false;
848
- node.value = value;
849
- return true;
850
- }
851
- /**
852
- * Delete the element at an index.
853
- * @remarks Time O(N), Space O(1)
854
- * @param index - Zero-based index.
855
- * @returns Removed element or undefined.
856
- */
857
- deleteAt(index) {
858
- if (index < 0 || index >= this._length)
859
- return;
860
- if (index === 0)
861
- return this.shift();
862
- if (index === this._length - 1)
863
- return this.pop();
864
- const removedNode = this.getNodeAt(index);
865
- const prevNode = removedNode.prev;
866
- const nextNode = removedNode.next;
867
- prevNode.next = nextNode;
868
- nextNode.prev = prevNode;
869
- this._length--;
870
- return removedNode.value;
871
- }
872
- /**
873
- * Delete the first match by value/node.
874
- * @remarks Time O(N), Space O(1)
875
- * @param [elementOrNode] - Element or node to remove.
876
- * @returns True if removed.
877
- */
878
- delete(elementOrNode) {
879
- const node = this.getNode(elementOrNode);
880
- if (!node)
881
- return false;
882
- if (node === this.head)
883
- this.shift();
884
- else if (node === this.tail)
885
- this.pop();
886
- else {
887
- const prevNode = node.prev;
888
- const nextNode = node.next;
889
- prevNode.next = nextNode;
890
- nextNode.prev = prevNode;
891
- this._length--;
892
- }
893
- return true;
894
- }
895
- /**
896
- * Check whether the list is empty.
897
- * @remarks Time O(1), Space O(1)
898
- * @returns True if length is 0.
899
- */
900
- isEmpty() {
901
- return this._length === 0;
902
- }
903
- /**
904
- * Remove all nodes and reset length.
905
- * @remarks Time O(N), Space O(1)
906
- * @returns void
907
- */
908
- clear() {
909
- this._head = undefined;
910
- this._tail = undefined;
911
- this._length = 0;
912
- }
913
- /**
914
- * Find the first value matching a predicate scanning forward.
915
- * @remarks Time O(N), Space O(1)
916
- * @param elementNodeOrPredicate - Element, node, or predicate to match.
917
- * @returns Matched value or undefined.
918
- */
919
- search(elementNodeOrPredicate) {
920
- const predicate = this._ensurePredicate(elementNodeOrPredicate);
921
- let current = this.head;
922
- while (current) {
923
- if (predicate(current))
924
- return current.value;
925
- current = current.next;
926
- }
927
- return undefined;
928
- }
929
- /**
930
- * Find the first value matching a predicate scanning backward.
931
- * @remarks Time O(N), Space O(1)
932
- * @param elementNodeOrPredicate - Element, node, or predicate to match.
933
- * @returns Matched value or undefined.
934
- */
935
- getBackward(elementNodeOrPredicate) {
936
- const predicate = this._ensurePredicate(elementNodeOrPredicate);
937
- let current = this.tail;
938
- while (current) {
939
- if (predicate(current))
940
- return current.value;
941
- current = current.prev;
942
- }
943
- return undefined;
944
- }
945
- /**
946
- * Reverse the list in place.
947
- * @remarks Time O(N), Space O(1)
948
- * @returns This list.
949
- */
950
- reverse() {
951
- let current = this.head;
952
- [this._head, this._tail] = [this.tail, this.head];
953
- while (current) {
954
- const next = current.next;
955
- [current.prev, current.next] = [current.next, current.prev];
956
- current = next;
957
- }
958
- return this;
959
- }
960
- /**
961
- * Set the equality comparator used to compare values.
962
- * @remarks Time O(1), Space O(1)
963
- * @param equals - Equality predicate (a, b) → boolean.
964
- * @returns This list.
965
- */
966
- setEquality(equals) {
967
- this._equals = equals;
968
- return this;
969
- }
970
- /**
971
- * Deep clone this list (values are copied by reference).
972
- * @remarks Time O(N), Space O(N)
973
- * @returns A new list with the same element sequence.
974
- */
975
- clone() {
976
- const out = this._createInstance({ toElementFn: this._toElementFn, maxLen: this._maxLen });
977
- for (const v of this)
978
- out.push(v);
979
- return out;
980
- }
981
- /**
982
- * Filter values into a new list of the same class.
983
- * @remarks Time O(N), Space O(N)
984
- * @param callback - Predicate (value, index, list) → boolean to keep value.
985
- * @param [thisArg] - Value for `this` inside the callback.
986
- * @returns A new list with kept values.
987
- */
988
- filter(callback, thisArg) {
989
- const out = this._createInstance({ toElementFn: this._toElementFn, maxLen: this._maxLen });
990
- let index = 0;
991
- for (const v of this)
992
- if (callback.call(thisArg, v, index++, this))
993
- out.push(v);
994
- return out;
995
- }
996
- /**
997
- * Map values into a new list of the same class.
998
- * @remarks Time O(N), Space O(N)
999
- * @param callback - Mapping function (value, index, list) → newValue.
1000
- * @param [thisArg] - Value for `this` inside the callback.
1001
- * @returns A new list with mapped values.
1002
- */
1003
- mapSame(callback, thisArg) {
1004
- const out = this._createInstance({ toElementFn: this._toElementFn, maxLen: this._maxLen });
1005
- let index = 0;
1006
- for (const v of this) {
1007
- const mv = thisArg === undefined ? callback(v, index++, this) : callback.call(thisArg, v, index++, this);
1008
- out.push(mv);
1009
- }
1010
- return out;
1011
- }
1012
- /**
1013
- * Map values into a new list (possibly different element type).
1014
- * @remarks Time O(N), Space O(N)
1015
- * @template EM
1016
- * @template RM
1017
- * @param callback - Mapping function (value, index, list) → newElement.
1018
- * @param [options] - Options for the output list (e.g., maxLen, toElementFn).
1019
- * @param [thisArg] - Value for `this` inside the callback.
1020
- * @returns A new DoublyLinkedList with mapped values.
1021
- */
1022
- map(callback, options, thisArg) {
1023
- const out = this._createLike([], Object.assign(Object.assign({}, (options !== null && options !== void 0 ? options : {})), { maxLen: this._maxLen }));
1024
- let index = 0;
1025
- for (const v of this)
1026
- out.push(callback.call(thisArg, v, index++, this));
1027
- return out;
1028
- }
1029
- /**
1030
- * (Protected) Create or return a node for the given input (node or raw element).
1031
- * @remarks Time O(1), Space O(1)
1032
- * @param elementOrNode - Element value or node to normalize.
1033
- * @returns A DoublyLinkedListNode for the provided input.
1034
- */
1035
- _ensureNode(elementOrNode) {
1036
- if (this.isNode(elementOrNode))
1037
- return elementOrNode;
1038
- return new DoublyLinkedListNode(elementOrNode);
1039
- }
1040
- /**
1041
- * (Protected) Normalize input into a predicate over nodes.
1042
- * @remarks Time O(1), Space O(1)
1043
- * @param elementNodeOrPredicate - Element, node, or node predicate.
1044
- * @returns A predicate function taking a node and returning true/false.
1045
- */
1046
- _ensurePredicate(elementNodeOrPredicate) {
1047
- if (this.isNode(elementNodeOrPredicate)) {
1048
- const target = elementNodeOrPredicate;
1049
- return (node) => node === target;
1050
- }
1051
- if (typeof elementNodeOrPredicate === 'function') {
1052
- return elementNodeOrPredicate;
1053
- }
1054
- const value = elementNodeOrPredicate;
1055
- return (node) => this._equals(node.value, value);
1056
- }
1057
- /**
1058
- * (Protected) Get the previous node of a given node.
1059
- * @remarks Time O(1), Space O(1)
1060
- * @param node - A node in the list.
1061
- * @returns Previous node or undefined.
1062
- */
1063
- _getPrevNode(node) {
1064
- return node.prev;
1065
- }
1066
- /**
1067
- * (Protected) Create an empty instance of the same concrete class.
1068
- * @remarks Time O(1), Space O(1)
1069
- * @param [options] - Options forwarded to the constructor.
1070
- * @returns An empty like-kind list instance.
1071
- */
1072
- _createInstance(options) {
1073
- const Ctor = this.constructor;
1074
- return new Ctor([], options);
1075
- }
1076
- /**
1077
- * (Protected) Create a like-kind instance and seed it from an iterable.
1078
- * @remarks Time O(N), Space O(N)
1079
- * @template EM
1080
- * @template RM
1081
- * @param [elements] - Iterable used to seed the new list.
1082
- * @param [options] - Options forwarded to the constructor.
1083
- * @returns A like-kind DoublyLinkedList instance.
1084
- */
1085
- _createLike(elements = [], options) {
1086
- const Ctor = this.constructor;
1087
- return new Ctor(elements, options);
1088
- }
1089
- *_getIterator() {
1090
- let current = this.head;
1091
- while (current) {
1092
- yield current.value;
1093
- current = current.next;
1094
- }
1095
- }
1096
- *_getReverseIterator() {
1097
- let current = this.tail;
1098
- while (current) {
1099
- yield current.value;
1100
- current = current.prev;
1101
- }
1102
- }
1103
- *_getNodeIterator() {
1104
- let current = this.head;
1105
- while (current) {
1106
- yield current;
1107
- current = current.next;
1108
- }
1109
- }
1110
- }
1111
- exports.DoublyLinkedList = DoublyLinkedList;