data-structure-typed 2.5.0 → 2.5.1

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 (222) hide show
  1. package/.vitepress/cache/deps_temp_51f5f1b0/chunk-7OIKW5WK.js +12984 -0
  2. package/.vitepress/cache/deps_temp_51f5f1b0/package.json +3 -0
  3. package/.vitepress/cache/deps_temp_51f5f1b0/vitepress___@vue_devtools-api.js +4505 -0
  4. package/.vitepress/cache/deps_temp_51f5f1b0/vitepress___@vueuse_core.js +9731 -0
  5. package/.vitepress/cache/deps_temp_51f5f1b0/vue.js +347 -0
  6. package/CHANGELOG.md +3 -1
  7. package/README.md +63 -26
  8. package/dist/cjs/binary-tree.cjs +23698 -0
  9. package/dist/cjs/graph.cjs +5236 -0
  10. package/dist/cjs/hash.cjs +1262 -0
  11. package/dist/cjs/heap.cjs +1540 -0
  12. package/dist/cjs/index.cjs +28244 -14795
  13. package/dist/cjs/linked-list.cjs +4370 -0
  14. package/dist/cjs/matrix.cjs +1042 -0
  15. package/dist/cjs/priority-queue.cjs +1314 -0
  16. package/dist/cjs/queue.cjs +4090 -0
  17. package/dist/cjs/stack.cjs +861 -0
  18. package/dist/cjs/trie.cjs +1173 -0
  19. package/dist/cjs-legacy/binary-tree.cjs +23730 -0
  20. package/dist/cjs-legacy/graph.cjs +5234 -0
  21. package/dist/cjs-legacy/hash.cjs +1262 -0
  22. package/dist/cjs-legacy/heap.cjs +1537 -0
  23. package/dist/cjs-legacy/index.cjs +28239 -14790
  24. package/dist/cjs-legacy/linked-list.cjs +4376 -0
  25. package/dist/cjs-legacy/matrix.cjs +1045 -0
  26. package/dist/cjs-legacy/priority-queue.cjs +1312 -0
  27. package/dist/cjs-legacy/queue.cjs +4088 -0
  28. package/dist/cjs-legacy/stack.cjs +861 -0
  29. package/dist/cjs-legacy/trie.cjs +1172 -0
  30. package/dist/esm/binary-tree.mjs +23683 -0
  31. package/dist/esm/graph.mjs +5223 -0
  32. package/dist/esm/hash.mjs +1259 -0
  33. package/dist/esm/heap.mjs +1534 -0
  34. package/dist/esm/index.mjs +28242 -14796
  35. package/dist/esm/linked-list.mjs +4363 -0
  36. package/dist/esm/matrix.mjs +1038 -0
  37. package/dist/esm/priority-queue.mjs +1310 -0
  38. package/dist/esm/queue.mjs +4086 -0
  39. package/dist/esm/stack.mjs +859 -0
  40. package/dist/esm/trie.mjs +1170 -0
  41. package/dist/esm-legacy/binary-tree.mjs +23715 -0
  42. package/dist/esm-legacy/graph.mjs +5221 -0
  43. package/dist/esm-legacy/hash.mjs +1259 -0
  44. package/dist/esm-legacy/heap.mjs +1531 -0
  45. package/dist/esm-legacy/index.mjs +28237 -14791
  46. package/dist/esm-legacy/linked-list.mjs +4369 -0
  47. package/dist/esm-legacy/matrix.mjs +1041 -0
  48. package/dist/esm-legacy/priority-queue.mjs +1308 -0
  49. package/dist/esm-legacy/queue.mjs +4084 -0
  50. package/dist/esm-legacy/stack.mjs +859 -0
  51. package/dist/esm-legacy/trie.mjs +1169 -0
  52. package/dist/types/data-structures/base/index.d.ts +1 -0
  53. package/dist/types/data-structures/base/iterable-entry-base.d.ts +8 -8
  54. package/dist/types/data-structures/base/linear-base.d.ts +3 -3
  55. package/dist/types/data-structures/binary-tree/avl-tree.d.ts +240 -0
  56. package/dist/types/data-structures/binary-tree/binary-indexed-tree.d.ts +280 -0
  57. package/dist/types/data-structures/binary-tree/binary-tree.d.ts +502 -2
  58. package/dist/types/data-structures/binary-tree/bst.d.ts +481 -1
  59. package/dist/types/data-structures/binary-tree/red-black-tree.d.ts +380 -0
  60. package/dist/types/data-structures/binary-tree/segment-tree.d.ts +120 -1
  61. package/dist/types/data-structures/binary-tree/tree-map.d.ts +2764 -384
  62. package/dist/types/data-structures/binary-tree/tree-multi-map.d.ts +2753 -353
  63. package/dist/types/data-structures/binary-tree/tree-multi-set.d.ts +2241 -321
  64. package/dist/types/data-structures/binary-tree/tree-set.d.ts +2554 -274
  65. package/dist/types/data-structures/graph/abstract-graph.d.ts +4 -4
  66. package/dist/types/data-structures/graph/directed-graph.d.ts +200 -0
  67. package/dist/types/data-structures/graph/undirected-graph.d.ts +180 -0
  68. package/dist/types/data-structures/hash/hash-map.d.ts +230 -10
  69. package/dist/types/data-structures/heap/heap.d.ts +280 -0
  70. package/dist/types/data-structures/linked-list/doubly-linked-list.d.ts +343 -3
  71. package/dist/types/data-structures/linked-list/singly-linked-list.d.ts +303 -3
  72. package/dist/types/data-structures/linked-list/skip-linked-list.d.ts +362 -2
  73. package/dist/types/data-structures/matrix/matrix.d.ts +160 -0
  74. package/dist/types/data-structures/queue/deque.d.ts +304 -4
  75. package/dist/types/data-structures/queue/queue.d.ts +240 -0
  76. package/dist/types/data-structures/stack/stack.d.ts +200 -0
  77. package/dist/types/data-structures/trie/trie.d.ts +244 -4
  78. package/dist/types/interfaces/graph.d.ts +1 -1
  79. package/dist/types/types/common.d.ts +2 -2
  80. package/dist/types/types/data-structures/heap/heap.d.ts +1 -0
  81. package/dist/types/types/data-structures/priority-queue/priority-queue.d.ts +1 -0
  82. package/dist/types/types/utils/validate-type.d.ts +4 -4
  83. package/dist/umd/data-structure-typed.js +28022 -14573
  84. package/dist/umd/data-structure-typed.min.js +9 -3
  85. package/docs-site-docusaurus/README.md +41 -0
  86. package/docs-site-docusaurus/docs/api/README.md +52 -0
  87. package/docs-site-docusaurus/docs/api/classes/AVLTree.md +6130 -0
  88. package/docs-site-docusaurus/docs/api/classes/AVLTreeNode.md +282 -0
  89. package/docs-site-docusaurus/docs/api/classes/AbstractGraph.md +2266 -0
  90. package/docs-site-docusaurus/docs/api/classes/BST.md +5831 -0
  91. package/docs-site-docusaurus/docs/api/classes/BSTNode.md +333 -0
  92. package/docs-site-docusaurus/docs/api/classes/BinaryIndexedTree.md +455 -0
  93. package/docs-site-docusaurus/docs/api/classes/BinaryTree.md +4647 -0
  94. package/docs-site-docusaurus/docs/api/classes/BinaryTreeNode.md +331 -0
  95. package/docs-site-docusaurus/docs/api/classes/Deque.md +2767 -0
  96. package/docs-site-docusaurus/docs/api/classes/DirectedGraph.md +2999 -0
  97. package/docs-site-docusaurus/docs/api/classes/DoublyLinkedList.md +2685 -0
  98. package/docs-site-docusaurus/docs/api/classes/DoublyLinkedListNode.md +221 -0
  99. package/docs-site-docusaurus/docs/api/classes/FibonacciHeap.md +253 -0
  100. package/docs-site-docusaurus/docs/api/classes/FibonacciHeapNode.md +21 -0
  101. package/docs-site-docusaurus/docs/api/classes/HashMap.md +1333 -0
  102. package/docs-site-docusaurus/docs/api/classes/Heap.md +1881 -0
  103. package/docs-site-docusaurus/docs/api/classes/IterableElementBase.md +800 -0
  104. package/docs-site-docusaurus/docs/api/classes/IterableEntryBase.md +644 -0
  105. package/docs-site-docusaurus/docs/api/classes/LinearBase.md +1632 -0
  106. package/docs-site-docusaurus/docs/api/classes/LinearLinkedBase.md +1853 -0
  107. package/docs-site-docusaurus/docs/api/classes/LinkedHashMap.md +1108 -0
  108. package/docs-site-docusaurus/docs/api/classes/LinkedListNode.md +156 -0
  109. package/docs-site-docusaurus/docs/api/classes/LinkedListQueue.md +2824 -0
  110. package/docs-site-docusaurus/docs/api/classes/MapGraph.md +2929 -0
  111. package/docs-site-docusaurus/docs/api/classes/Matrix.md +1026 -0
  112. package/docs-site-docusaurus/docs/api/classes/MaxHeap.md +1866 -0
  113. package/docs-site-docusaurus/docs/api/classes/MaxPriorityQueue.md +1883 -0
  114. package/docs-site-docusaurus/docs/api/classes/MinHeap.md +1879 -0
  115. package/docs-site-docusaurus/docs/api/classes/MinPriorityQueue.md +1882 -0
  116. package/docs-site-docusaurus/docs/api/classes/Navigator.md +109 -0
  117. package/docs-site-docusaurus/docs/api/classes/PriorityQueue.md +1839 -0
  118. package/docs-site-docusaurus/docs/api/classes/Queue.md +2244 -0
  119. package/docs-site-docusaurus/docs/api/classes/RedBlackTree.md +6374 -0
  120. package/docs-site-docusaurus/docs/api/classes/SegmentTree.md +372 -0
  121. package/docs-site-docusaurus/docs/api/classes/SinglyLinkedList.md +2897 -0
  122. package/docs-site-docusaurus/docs/api/classes/SinglyLinkedListNode.md +169 -0
  123. package/docs-site-docusaurus/docs/api/classes/SkipList.md +1229 -0
  124. package/docs-site-docusaurus/docs/api/classes/Stack.md +1573 -0
  125. package/docs-site-docusaurus/docs/api/classes/TreeMap.md +1257 -0
  126. package/docs-site-docusaurus/docs/api/classes/TreeMultiMap.md +1475 -0
  127. package/docs-site-docusaurus/docs/api/classes/TreeSet.md +1117 -0
  128. package/docs-site-docusaurus/docs/api/classes/Trie.md +1708 -0
  129. package/docs-site-docusaurus/docs/api/classes/TrieNode.md +199 -0
  130. package/docs-site-docusaurus/docs/api/classes/UndirectedGraph.md +2979 -0
  131. package/docs-site-docusaurus/docs/guide/_category_.json +6 -0
  132. package/docs-site-docusaurus/docs/guide/architecture.md +613 -0
  133. package/docs-site-docusaurus/docs/guide/concepts.md +420 -0
  134. package/docs-site-docusaurus/docs/guide/guides.md +611 -0
  135. package/docs-site-docusaurus/docs/guide/installation.md +60 -0
  136. package/docs-site-docusaurus/docs/guide/integrations.md +823 -0
  137. package/docs-site-docusaurus/docs/guide/overview.md +638 -0
  138. package/docs-site-docusaurus/docs/guide/performance.md +833 -0
  139. package/docs-site-docusaurus/docs/guide/quick-start.md +73 -0
  140. package/docs-site-docusaurus/docusaurus.config.ts +159 -0
  141. package/docs-site-docusaurus/fix-mdx-generics.mjs +75 -0
  142. package/docs-site-docusaurus/package-lock.json +18667 -0
  143. package/docs-site-docusaurus/package.json +50 -0
  144. package/docs-site-docusaurus/prefix-class-to-methods.mjs +48 -0
  145. package/docs-site-docusaurus/sidebars.ts +23 -0
  146. package/docs-site-docusaurus/sort-protected.mjs +87 -0
  147. package/docs-site-docusaurus/src/css/custom.css +96 -0
  148. package/docs-site-docusaurus/src/pages/index.module.css +13 -0
  149. package/docs-site-docusaurus/src/pages/index.tsx +71 -0
  150. package/docs-site-docusaurus/src/pages/markdown-page.md +7 -0
  151. package/docs-site-docusaurus/src/theme/TOCItems/index.tsx +34 -0
  152. package/docs-site-docusaurus/static/.nojekyll +0 -0
  153. package/docs-site-docusaurus/static/img/docusaurus-social-card.jpg +0 -0
  154. package/docs-site-docusaurus/static/img/docusaurus.png +0 -0
  155. package/docs-site-docusaurus/static/img/favicon.ico +0 -0
  156. package/docs-site-docusaurus/static/img/favicon.png +0 -0
  157. package/docs-site-docusaurus/static/img/logo-180.png +0 -0
  158. package/docs-site-docusaurus/static/img/logo.jpg +0 -0
  159. package/docs-site-docusaurus/static/img/logo.png +0 -0
  160. package/docs-site-docusaurus/static/img/logo.svg +1 -0
  161. package/docs-site-docusaurus/static/img/og-image.png +0 -0
  162. package/docs-site-docusaurus/static/img/undraw_docusaurus_mountain.svg +171 -0
  163. package/docs-site-docusaurus/static/img/undraw_docusaurus_react.svg +170 -0
  164. package/docs-site-docusaurus/static/img/undraw_docusaurus_tree.svg +40 -0
  165. package/docs-site-docusaurus/static/robots.txt +4 -0
  166. package/docs-site-docusaurus/typedoc.json +23 -0
  167. package/package.json +106 -10
  168. package/src/data-structures/base/index.ts +1 -0
  169. package/src/data-structures/base/iterable-entry-base.ts +8 -8
  170. package/src/data-structures/base/linear-base.ts +3 -3
  171. package/src/data-structures/binary-tree/avl-tree.ts +240 -0
  172. package/src/data-structures/binary-tree/binary-indexed-tree.ts +281 -1
  173. package/src/data-structures/binary-tree/binary-tree.ts +502 -2
  174. package/src/data-structures/binary-tree/bst.ts +481 -1
  175. package/src/data-structures/binary-tree/red-black-tree.ts +380 -0
  176. package/src/data-structures/binary-tree/segment-tree.ts +121 -2
  177. package/src/data-structures/binary-tree/tree-map.ts +2862 -482
  178. package/src/data-structures/binary-tree/tree-multi-map.ts +2963 -563
  179. package/src/data-structures/binary-tree/tree-multi-set.ts +2399 -479
  180. package/src/data-structures/binary-tree/tree-set.ts +2685 -405
  181. package/src/data-structures/graph/abstract-graph.ts +4 -4
  182. package/src/data-structures/graph/directed-graph.ts +200 -0
  183. package/src/data-structures/graph/undirected-graph.ts +180 -0
  184. package/src/data-structures/hash/hash-map.ts +235 -15
  185. package/src/data-structures/heap/heap.ts +280 -0
  186. package/src/data-structures/linked-list/doubly-linked-list.ts +343 -3
  187. package/src/data-structures/linked-list/singly-linked-list.ts +303 -3
  188. package/src/data-structures/linked-list/skip-linked-list.ts +362 -2
  189. package/src/data-structures/matrix/matrix.ts +161 -1
  190. package/src/data-structures/queue/deque.ts +305 -5
  191. package/src/data-structures/queue/queue.ts +240 -0
  192. package/src/data-structures/stack/stack.ts +200 -0
  193. package/src/data-structures/trie/trie.ts +245 -5
  194. package/src/interfaces/graph.ts +1 -1
  195. package/src/types/common.ts +2 -2
  196. package/src/types/data-structures/heap/heap.ts +1 -0
  197. package/src/types/data-structures/priority-queue/priority-queue.ts +1 -0
  198. package/src/types/utils/validate-type.ts +4 -4
  199. package/vercel.json +6 -0
  200. package/dist/leetcode/avl-tree-counter.mjs +0 -2957
  201. package/dist/leetcode/avl-tree-multi-map.mjs +0 -2889
  202. package/dist/leetcode/avl-tree.mjs +0 -2720
  203. package/dist/leetcode/binary-tree.mjs +0 -1594
  204. package/dist/leetcode/bst.mjs +0 -2398
  205. package/dist/leetcode/deque.mjs +0 -683
  206. package/dist/leetcode/directed-graph.mjs +0 -1733
  207. package/dist/leetcode/doubly-linked-list.mjs +0 -709
  208. package/dist/leetcode/hash-map.mjs +0 -493
  209. package/dist/leetcode/heap.mjs +0 -542
  210. package/dist/leetcode/max-heap.mjs +0 -375
  211. package/dist/leetcode/max-priority-queue.mjs +0 -383
  212. package/dist/leetcode/min-heap.mjs +0 -363
  213. package/dist/leetcode/min-priority-queue.mjs +0 -371
  214. package/dist/leetcode/priority-queue.mjs +0 -363
  215. package/dist/leetcode/queue.mjs +0 -943
  216. package/dist/leetcode/red-black-tree.mjs +0 -2765
  217. package/dist/leetcode/singly-linked-list.mjs +0 -754
  218. package/dist/leetcode/stack.mjs +0 -217
  219. package/dist/leetcode/tree-counter.mjs +0 -3039
  220. package/dist/leetcode/tree-multi-map.mjs +0 -2913
  221. package/dist/leetcode/trie.mjs +0 -413
  222. package/dist/leetcode/undirected-graph.mjs +0 -1650
@@ -0,0 +1,6 @@
1
+ {
2
+ "label": "Guide",
3
+ "position": 2,
4
+ "collapsible": true,
5
+ "collapsed": false
6
+ }
@@ -0,0 +1,613 @@
1
+ ---
2
+ sidebar_label: "ARCHITECTURE"
3
+ description: "Internal architecture: inheritance hierarchy, iterator protocol, memory layout, and algorithmic guarantees."
4
+ ---
5
+
6
+ # ARCHITECTURE
7
+
8
+ Understand why this library is designed the way it is, and how it works internally.
9
+
10
+ **[Back to README](/.md) • [See Performance](/guide/performance.md) • [Real Examples](/guide/guides.md)**
11
+
12
+ ---
13
+
14
+ ## Table of Contents
15
+
16
+ 1. [Design Philosophy](#design-philosophy)
17
+ 2. [The Big Three Pain Points](#the-big-three-pain-points)
18
+ 3. [Why Deque is 484x Faster](#why-deque-is-484x-faster)
19
+ 4. [Iterator Protocol Design](#iterator-protocol-design)
20
+ 5. [Self-Balancing Strategy](#self-balancing-strategy)
21
+ 6. [V8 JIT Optimizations](#v8-jit-optimizations)
22
+
23
+ ---
24
+
25
+ ## Design Philosophy
26
+
27
+ ### Core Principles
28
+
29
+ 1. **Practicality**: Follows ES6 standards, ESNext patterns, simple method names
30
+ 2. **Extensibility**: OOP inheritance for all data structures
31
+ 3. **Modularization**: Independent NPM packages, no bloat
32
+ 4. **Efficiency**: Time/space complexity comparable to native JS
33
+ 5. **Maintainability**: Open-source standards, TDD, CI/CD
34
+ 6. **Testability**: Automated unit + performance testing
35
+ 7. **Reusability**: Fully decoupled, minimized side effects
36
+ 8. **Security**: Read-write separation, safe member access
37
+
38
+ ### API Design: Unified Interface
39
+
40
+ Instead of learning different APIs for each library:
41
+
42
+ ```javascript
43
+ // ❌ Different libraries, different APIs
44
+ const queue = new Queue();
45
+ queue.enqueue(1); // Library A
46
+ queue.push(1); // Library B
47
+ queue.offer(1); // Library C (Java style)
48
+
49
+ // ✅ data-structure-typed: Consistent everywhere
50
+ const queue = new Queue();
51
+ const deque = new Deque();
52
+ const stack = new Stack();
53
+
54
+ // All use THE SAME 4 methods
55
+ queue.push(item); // Add
56
+ deque.unshift(item); // Add to front
57
+ stack.pop(); // Remove
58
+ queue.shift(); // Remove from front
59
+ ```
60
+
61
+ **Why?** Because developers already know `push`, `pop`, `shift`, `unshift` from Arrays. Zero new mental models needed.
62
+
63
+ ---
64
+
65
+ ## The Big Three Pain Points
66
+
67
+ ### Pain Point 1: Performance Wall
68
+
69
+ When operations become bottlenecks:
70
+
71
+ ```javascript
72
+ const games = [
73
+ { id: 'game_001', name: 'Tetris', score: 9850 },
74
+ { id: 'game_002', name: 'Minecraft', score: 9750 },
75
+ { id: 'game_003', name: 'Grand Theft Auto V', score: 9600 },
76
+ { id: 'game_004', name: 'Wii Sports', score: 9500 },
77
+ { id: 'game_005', name: 'PlayerUnknown\'s Battlegrounds', score: 9200 },
78
+ { id: 'game_006', name: 'Fortnite', score: 9100 },
79
+ { id: 'game_007', name: 'League of Legends', score: 8950 },
80
+ { id: 'game_008', name: 'The Legend of Zelda: Breath of the Wild', score: 8850 },
81
+ { id: 'game_009', name: 'Elden Ring', score: 8700 },
82
+ { id: 'game_010', name: 'Super Mario Bros', score: 8600 },
83
+ ];
84
+ // ❌ Repeated sorting slows everything
85
+ const scores = [];
86
+ for (const game of games) {
87
+ scores.push(game.score);
88
+ scores.sort((a, b) => b - a); // O(n log n) every time!
89
+ }
90
+ ```
91
+
92
+ ```javascript
93
+ // ✅ Auto-maintained sorted order
94
+ const rankings = new RedBlackTree(games, {
95
+ toEntryFn: (game) => [game.id, game.score],
96
+ comparator: (a, b) => b - a,
97
+ }); // O(n log n) in total!
98
+ // Iteration is always sorted!
99
+ ```
100
+
101
+ **Real Impact:**
102
+
103
+ - Competitive programming: TLE → AC (Time Exceeded to Accepted)
104
+ - Real-time systems: P99 latency 500ms → 5ms
105
+ - Message queues: 100 msg/sec → 10,000 msg/sec
106
+
107
+ ### Pain Point 2: API Chaos
108
+
109
+ Different libraries use completely different method names:
110
+
111
+ | Operation | ArrayList | Queue | ArrayDeque | LinkedList |
112
+ |--------------|-----------|--------------|---------------|---------------|
113
+ | Add end | add() | offer() | push() | add() |
114
+ | Remove end | remove() | - | pop() | removeLast() |
115
+ | Remove start | remove(0) | poll() | removeFirst() | removeFirst() |
116
+ | Add start | add(0, e) | offerFirst() | unshift() | addFirst() |
117
+
118
+ **Result**: Developers must memorize N different APIs.
119
+
120
+ **Solution**: Use 4 consistent methods everywhere:
121
+
122
+ ```typescript
123
+ // Every linear structure uses same API
124
+ const deque = new Deque();
125
+ const queue = new Queue();
126
+ const list = new DoublyLinkedList();
127
+
128
+ // All support these 4 methods:
129
+ structure.push(item); // Add to end
130
+ structure.pop(); // Remove from end
131
+ structure.shift(); // Remove from start
132
+ structure.unshift(item); // Add to start
133
+ ```
134
+
135
+ ### Pain Point 3: Conversion Hell
136
+
137
+ Bouncing data between structures wastes cycles:
138
+
139
+ ```typescript
140
+ // ❌ Painful way: conversions everywhere
141
+ const tree = new TreeLibrary(data);
142
+ const filtered = tree.toArray()
143
+ .filter(x => x > 5) // Convert to Array
144
+ .map(x => x * 2) // Still Array
145
+ .sort((a, b) => b - a); // Array sort is O(n log n)
146
+
147
+ // Lost the tree's sorted benefits!
148
+ ```
149
+
150
+ ```typescript
151
+ // ✅ Clean way: operations work directly
152
+ const tree = new RedBlackTree<number, number>();
153
+ const result = tree
154
+ .filter(v => (v ?? 0) > 5) // Direct on tree
155
+ .map((v, k) => [k, (v ?? 0) * 2]) // Still on tree
156
+ .reduce((sum, v) => sum + (v ?? 0), 0); // Still on tree
157
+
158
+ // Zero conversions, tree structure maintained!
159
+ ```
160
+
161
+ ---
162
+
163
+ ## Why Deque is 484x Faster
164
+
165
+ ### The Problem: Array.shift()
166
+
167
+ ```javascript
168
+ // What happens when you shift from an array:
169
+ const arr = [1, 2, 3, 4, 5];
170
+ arr.shift(); // Remove 1
171
+
172
+ // JavaScript engine must:
173
+ // 1. Create new memory for index 0
174
+ // 2. Copy element 2 → index 0
175
+ // 3. Copy element 3 → index 1
176
+ // 4. Copy element 4 → index 2
177
+ // 5. Copy element 5 → index 3
178
+ // 6. Resize array
179
+
180
+ // For 100,000 elements: O(n) = 100,000 operations each time!
181
+ ```
182
+
183
+ Real benchmark:
184
+
185
+ ```javascript
186
+ const queue = [];
187
+ for (let i = 0; i < 100000; i++) queue.push(i);
188
+ for (let i = 0; i < 100000; i++) queue.shift();
189
+ // Time: 2829ms for 100,000 shifts ❌
190
+ ```
191
+
192
+ ### The Solution: Deque's Chunked Rings
193
+
194
+ ```javascript
195
+ // Deque implementation strategy:
196
+ // Instead of physical array, use chunked buckets
197
+
198
+ // bucket[0] bucket[1] bucket[2]
199
+ // [1,2,3,4,5] [6,7,8,9,10] [11,12,13]
200
+ // ^
201
+ // head pointer
202
+
203
+ // When you shift():
204
+ // Move pointer forward in bucket
205
+ // No copying until bucket is empty!
206
+ // Only then delete bucket (batch operation)
207
+ ```
208
+
209
+ Benchmark result:
210
+
211
+ ```javascript
212
+ const deque = new Deque();
213
+ for (let i = 0; i < 100000; i++) deque.push(i);
214
+ for (let i = 0; i < 100000; i++) deque.shift();
215
+ // Time: 5.83ms for 100,000 shifts ✅
216
+
217
+ // 2829ms / 5.83ms = 485x faster!
218
+ ```
219
+
220
+ ### Why This Works
221
+
222
+ **Batching Operations**: Instead of reindexing on every shift, Deque batches operations into chunks. Only when an entire chunk is consumed does it get cleaned up.
223
+
224
+ **Memory Locality**: Chunked structure is better for CPU cache than scattered reindexing operations.
225
+
226
+ **Pointer Movement**: Shifting is just moving a pointer forward in memory, which is a CPU register operation (nanoseconds).
227
+
228
+ ---
229
+
230
+ ## Iterator Protocol Design
231
+
232
+ ### The Hidden Superpower
233
+
234
+ Every data structure implements JavaScript's iterator protocol:
235
+
236
+ ```javascript
237
+ // Why this matters:
238
+ const tree = new RedBlackTree([5, 2, 8]);
239
+
240
+ // All of these work automatically:
241
+ [...tree] // Spread operator
242
+ for (const x of tree) {
243
+ } // for...of loop
244
+ const [a, b, c] = tree // Destructuring
245
+ new Set(tree) // Set constructor
246
+ Array.from(tree) // Array.from
247
+
248
+ // No special methods needed!
249
+ // Just implement Symbol.iterator
250
+ ```
251
+
252
+ ### Implementation Strategy
253
+
254
+ ```typescript
255
+ class CustomStructure<T> {
256
+ private items: T[] = [];
257
+
258
+ // One method makes everything work
259
+ * [Symbol.iterator]() {
260
+ for (const item of this.items) {
261
+ yield item;
262
+ }
263
+ }
264
+
265
+ push(...item: T[]) {
266
+ this.items.concat(item);
267
+ }
268
+ }
269
+
270
+ // Now the structure works everywhere:
271
+ const struct = new CustomStructure();
272
+ struct.push(1, 2, 3);
273
+
274
+ // All of these work automatically:
275
+ [...struct]; // [1, 2, 3]
276
+ for (const x of struct) {
277
+ } // Loops 1, 2, 3
278
+ ```
279
+
280
+ ### Why Iterator Protocol?
281
+
282
+ 1. **Consistency**: Uses same interface as Arrays and Maps
283
+ 2. **Zero Learning Curve**: Developers already know `for...of`
284
+ 3. **Interoperability**: Works with spread, destructuring, Set constructor
285
+ 4. **Future-Proof**: JavaScript standard, not library-specific
286
+
287
+ ---
288
+
289
+ ## Self-Balancing Strategy
290
+
291
+ ### The Problem: Unbalanced Trees
292
+
293
+ ```javascript
294
+ // Create an unbalanced tree:
295
+ const bst = new BST();
296
+ [1, 2, 3, 4, 5].forEach(x => bst.add(x));
297
+
298
+ // 1
299
+ // \
300
+ // 2
301
+ // \
302
+ // 3
303
+ // \
304
+ // 4
305
+ // \
306
+ // 5
307
+
308
+ // This becomes a linked list! O(n) instead of O(log n)
309
+ ```
310
+
311
+ ### Red-Black Tree Solution
312
+
313
+ **Rules:**
314
+
315
+ 1. Every node is either Red or Black
316
+ 2. Root is always Black
317
+ 3. Red nodes have Black children (no consecutive Reds)
318
+ 4. All paths to null have same number of Black nodes
319
+
320
+ **Result**: Tree height limited to ~2 * log(n), guaranteeing O(log n)
321
+
322
+ ```javascript
323
+ const rbTree = new RedBlackTree([1, 2, 3, 4, 5]);
324
+
325
+ // 3(B) Balanced!
326
+ // / \
327
+ // 2(B) 4(R)
328
+ // / \
329
+ // 1(R) 5(B)
330
+
331
+ // Even with sequential inserts: O(log n) guaranteed!
332
+ ```
333
+
334
+ ### AVL Tree Alternative
335
+
336
+ **Stricter balance requirement**: Height difference ≤ 1
337
+
338
+ ```javascript
339
+ // 3
340
+ // / \
341
+ // 2 4
342
+ // / \
343
+ // 1 5
344
+
345
+ // More strictly balanced = better search
346
+ // Trade-off: Slower insertions/deletions (more rebalancing)
347
+ ```
348
+
349
+ ### SkipList: Probabilistic Balancing
350
+
351
+ Unlike Red-Black Tree or AVL Tree which rebalance deterministically, **SkipList** uses randomization:
352
+
353
+ ```
354
+ Level 3: ──────────────────────────► 50
355
+ Level 2: ────────► 20 ──────────────► 50
356
+ Level 1: ──► 10 ──► 20 ──► 30 ──► 50 ──► 70
357
+ ```
358
+
359
+ Each node is promoted to a higher level with probability 0.5 (configurable). This gives O(log n) **average** performance — equivalent to Red-Black Tree in practice, but implemented with much simpler code.
360
+
361
+ **When to use SkipList vs TreeMap:**
362
+ - Both provide identical APIs (`NavigableMap` semantics)
363
+ - SkipList: simpler codebase, constant factors slightly higher
364
+ - TreeMap (Red-Black Tree): guaranteed O(log n) worst-case
365
+
366
+ ---
367
+
368
+ ## Range Query Structures
369
+
370
+ ### SegmentTree
371
+
372
+ Stores aggregated values in a complete binary tree backed by a flat array:
373
+
374
+ ```
375
+ Array: [1, 3, 5, 7]
376
+
377
+ Tree: 16 (root = sum all)
378
+ / \
379
+ 4 12 (sum of halves)
380
+ / \ / \
381
+ 1 3 5 7 (leaves = original values)
382
+
383
+ Internal array: [_, 16, 4, 12, 1, 3, 5, 7] (1-indexed)
384
+ ```
385
+
386
+ Query `[1,2]` (3+5=8): combines nodes covering exactly that range in O(log n).
387
+
388
+ Supports any associative operation via `merger` function: sum, min, max, GCD, product, etc.
389
+
390
+ ### BinaryIndexedTree (Fenwick Tree)
391
+
392
+ A more compact structure for prefix sums only:
393
+
394
+ ```
395
+ Array: [1, 3, 5, 7, 9]
396
+
397
+ BIT tree (1-indexed):
398
+ T[1] = 1 (covers [1,1])
399
+ T[2] = 1+3 = 4 (covers [1,2])
400
+ T[3] = 5 (covers [3,3])
401
+ T[4] = 1+3+5+7=16 (covers [1,4])
402
+ T[5] = 9 (covers [5,5])
403
+ ```
404
+
405
+ Prefix sum uses bit tricks (`i -= i & -i`) to traverse only O(log n) nodes.
406
+
407
+ **SegmentTree vs BinaryIndexedTree:**
408
+ | | SegmentTree | BinaryIndexedTree |
409
+ |---|---|---|
410
+ | Operations | sum/min/max/any | sum only |
411
+ | Update | O(log n) | O(log n) |
412
+ | Query | O(log n) | O(log n) |
413
+ | Space | O(2n) | O(n) |
414
+ | Complexity | Higher | Lower |
415
+
416
+ ---
417
+
418
+ ## V8 JIT Optimizations
419
+
420
+ ### How V8 Makes This Fast
421
+
422
+ ```javascript
423
+ // V8 JIT optimizes data structures that:
424
+ // 1. Have predictable shapes (hidden classes)
425
+ // 2. Use consistent types
426
+ // 3. Have stable method calls
427
+
428
+ // ✅ Good for V8 JIT:
429
+ class Node {
430
+ constructor(value) {
431
+ this.value = value; // Always same type
432
+ this.left = null; // Always null or Node
433
+ this.right = null; // Always null or Node
434
+ }
435
+ }
436
+ ```
437
+
438
+ ```javascript
439
+ // ❌ Bad for V8 JIT:
440
+ class BadNode {
441
+ constructor(value) {
442
+ this.value = value;
443
+ this.left = value; // Sometimes Node, sometimes number
444
+ this.meta = null; // Added dynamically later
445
+ }
446
+ }
447
+
448
+ // Our library uses strict typing for this reason!
449
+ ```
450
+
451
+ ### Performance Benefit
452
+
453
+ ```javascript
454
+ // Predictable structure → V8 caches optimizations
455
+ // First call: Interpreted
456
+ // Subsequent calls: JIT compiled to native code
457
+
458
+ // Result: typically faster after warm-up (benchmarks should include warm-up runs)
459
+
460
+ const tree = new RedBlackTree();
461
+ for (let i = 0; i < 1000000; i++) {
462
+ tree.set(i, Math.random());
463
+ }
464
+ // Becomes near-native speed through JIT!
465
+ ```
466
+
467
+ ---
468
+
469
+ ## Method Chaining Architecture
470
+
471
+ ### Design Pattern
472
+
473
+ ```typescript
474
+ class TreeStructure<K, V> {
475
+ // Methods return `this` for chaining
476
+ filter(predicate: (v: V, k: K) => boolean): this {
477
+ // ... filter logic ...
478
+ return this; // Return structure, not Array!
479
+ }
480
+
481
+ map(mapper: (v: V, k: K) => V): this {
482
+ // ... map logic ...
483
+ return this; // Chain continues!
484
+ }
485
+
486
+ reduce(reducer: (acc: any, v: V, k: K) => any, init: any) {
487
+ // ... reduce logic ...
488
+ return result; // Terminal operation
489
+ }
490
+ }
491
+
492
+ // Result: Chainable on any structure
493
+ tree
494
+ .filter(x => x > 5)
495
+ .map(x => x * 2)
496
+ .reduce((a, v) => a + v, 0);
497
+ ```
498
+
499
+ ### Why This Matters
500
+
501
+ Traditional approach loses structure type:
502
+
503
+ ```javascript
504
+ // ❌ Loses type information
505
+ const result = tree.toArray() // Now it's Array[]
506
+ .filter(x => x > 5) // Still Array
507
+ .map(x => x * 2); // Still Array
508
+ // Lost O(log n) properties!
509
+ ```
510
+
511
+ ```javascript
512
+ // ✅ Preserves structure
513
+ const result = tree
514
+ .filter(x => x > 5) // Still RedBlackTree
515
+ .map(x => x * 2) // Still RedBlackTree
516
+ .reduce((a, v) => a + v);
517
+ // Properties maintained!
518
+ ```
519
+
520
+ ---
521
+
522
+ ## Memory Efficiency
523
+
524
+ ### Comparison
525
+
526
+ | Structure | Overhead | Notes |
527
+ |------------|----------|---------------------|
528
+ | Array | Low | Fixed size |
529
+ | LinkedList | High | Pointer per node |
530
+ | BST | Medium | 2 pointers per node |
531
+ | Deque | Very Low | Chunked, batched |
532
+ | Heap | Very Low | Array-based |
533
+
534
+ ### Deque Memory Strategy
535
+
536
+ ```javascript
537
+ // Instead of one big array:
538
+ // [ ][ ][ ][ ][ ][ ][ ][ ][ ][ ]
539
+
540
+ // Use chunks (buckets):
541
+ // bucket[0]: [1][2][3][4][5]
542
+ // bucket[1]: [6][7][8][9][10]
543
+
544
+ // Benefits:
545
+ // 1. Only allocate chunks needed
546
+ // 2. Reuse empty buckets
547
+ // 3. Better cache locality
548
+ // 4. Less fragmentation
549
+ ```
550
+
551
+ ---
552
+
553
+ ## Type Safety Architecture
554
+
555
+ ### Generic Type Parameters
556
+
557
+ ```typescript
558
+ // Custom object types
559
+ interface User {
560
+ id: number;
561
+ name: string;
562
+ age: number;
563
+ }
564
+
565
+ const userTree = new RedBlackTree<number, User>();
566
+ userTree.set(1, { id: 1, name: 'Alice', age: 30 });
567
+
568
+ // Type inference works:
569
+ const user = userTree.get(1); // Type: User | undefined
570
+ user?.name; // Type-safe access
571
+ ```
572
+
573
+ ### Comparator Custom Logic
574
+
575
+ ```typescript
576
+ type CustomObject = {
577
+ name: string;
578
+ priority: number;
579
+ };
580
+
581
+ // Default comparator (ascending)
582
+ const ascTree = new RedBlackTree<number>();
583
+
584
+ // Reversed comparator (descending)
585
+ const descTree = new RedBlackTree<number>([], {
586
+ comparator: (a, b) => b - a // Reverse comparison
587
+ });
588
+
589
+ // Works with any type
590
+ const objectTree = new RedBlackTree<CustomObject>([], {
591
+ comparator: (a, b) => a.priority - b.priority,
592
+ });
593
+
594
+ ```
595
+
596
+ ---
597
+
598
+ ## Summary: Design Checklist
599
+
600
+ - ✅ Unified API across all structures
601
+ - ✅ Iterator protocol implementation
602
+ - ✅ Method chaining architecture
603
+ - ✅ Self-balancing guarantees
604
+ - ✅ V8 JIT-friendly code
605
+ - ✅ Memory-efficient algorithms
606
+ - ✅ Full TypeScript support
607
+ - ✅ Production-ready error handling
608
+
609
+ ---
610
+
611
+ **Next:** [Check PERFORMANCE.md](/guide/performance.md) for benchmarks.
612
+
613
+ **Or:** [See GUIDES.md](/guide/guides.md) for implementation examples.