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,823 @@
1
+ ---
2
+ sidebar_label: "INTEGRATIONS"
3
+ description: "Integrate data-structure-typed with React, Express, NestJS, and other frameworks. Production-ready patterns."
4
+ ---
5
+
6
+ # INTEGRATIONS
7
+
8
+ How to use data-structure-typed with React, Express, Nest.js, and other frameworks.
9
+
10
+ **[Back to README](/.md) • [Code Examples](/guide/guides.md) • [Performance](/guide/performance.md)**
11
+
12
+ ---
13
+
14
+ ## Table of Contents
15
+
16
+ 1. [React Integration](#react-integration)
17
+ 2. [Express Integration](#express-integration)
18
+ 3. [Nest.js Integration](#nestjs-integration)
19
+ 4. [TypeScript Configuration](#typescript-configuration)
20
+
21
+ ---
22
+
23
+ ## React Integration
24
+
25
+ ### Use Case: Sorted State Management
26
+
27
+ ```tsx
28
+ import { useCallback, useMemo, useState } from 'react';
29
+ import { RedBlackTree } from 'data-structure-typed';
30
+
31
+ interface TodoItem {
32
+ id: number;
33
+ text: string;
34
+ completed: boolean;
35
+ priority: number;
36
+ }
37
+
38
+ /**
39
+ * ╔═════════════════════════════════════════════════════════════════════════╗
40
+ * ║ PERFORMANCE COMPARISON TABLE ║
41
+ * ╠═════════════════╦═══════════════════╦═════════════════╦═════════════════╣
42
+ * ║ Operation ║ RedBlackTree ║ Array ║ Speedup ║
43
+ * ╠═════════════════╬═══════════════════╬═════════════════╬═════════════════╣
44
+ * ║ Add todo ║ O(log n) ║ O(n log n) ║ Often much faster* ║
45
+ * ║ Delete todo ║ O(log n) ║ O(n) ║ Often faster* ║
46
+ * ║ Keep sorted ║ Automatic ✓ ║ Manual sort ✗ ║ Less code ║
47
+ * ║ Rebalancing ║ Self-balancing ✓ ║ N/A ║ N/A ║
48
+ * ╠═════════════════╩═══════════════════╩═════════════════╩══════════════════╣
49
+ * ║ *See PERFORMANCE.md for measured benchmarks and how results scale. ║
50
+ * ╚═════════════════════════════════════════════════════════════════════════╝
51
+ */
52
+ export default function TodoApp() {
53
+ const [text, setText] = useState('');
54
+ const [priority, setPriority] = useState(5);
55
+
56
+ const [todos, setTodos] = useState(() =>
57
+ new RedBlackTree<TodoItem>([], {
58
+ // Comparator ensures todos are ALWAYS sorted by priority (descending)
59
+ // RedBlackTree maintains this order automatically on every insertion
60
+ // With Array, you'd need to manually sort() after each add → expensive!
61
+ comparator: (a, b) => b.priority - a.priority
62
+ }));
63
+
64
+ const addTodo = useCallback(() => {
65
+ if (!text.trim()) return;
66
+
67
+ setTodos((prev) => {
68
+ const next = prev.clone();
69
+
70
+ // This insertion maintains sorted order automatically
71
+ // The Red-Black Tree algorithm handles all the balancing
72
+ next.add({
73
+ id: Date.now(),
74
+ text: text.trim(),
75
+ completed: false,
76
+ priority: Math.max(1, Math.min(10, priority)),
77
+ });
78
+ return next;
79
+ });
80
+
81
+ }, [text, priority]);
82
+
83
+ /**
84
+ * Delete a todo efficiently
85
+ *
86
+ * Performance Analysis:
87
+ * ──────────────────
88
+ * ✅ RedBlackTree.delete(): O(log n)
89
+ * - For 1000 items: ~10 tree operations
90
+ * - No need to shift array elements
91
+ * - Red-Black Tree rebalances automatically
92
+ *
93
+ * ❌ Array Alternative:
94
+ * - Array.findIndex(): O(n) to find the item
95
+ * - Array.splice(): O(n) to remove and shift all elements
96
+ * - For 1000 items: ~500 operations per delete
97
+ * - Note: Actual wall-clock impact depends on your workload (rendering, GC, object shapes, etc.).
98
+ */
99
+ const deleteTodo = useCallback((todo: TodoItem) => {
100
+ setTodos((prev) => {
101
+ const next = prev.clone();
102
+ next.delete(todo); // ← O(log n) deletion
103
+ return next;
104
+ });
105
+ }, []);
106
+
107
+ const todoList = useMemo(() => [...todos.keys()], [todos]);
108
+
109
+ return (
110
+ <div className="todo-app">
111
+ <h2>Priority Todos (Auto-Sorted)</h2>
112
+ <div className="input-section">
113
+ <input
114
+ type="text"
115
+ placeholder="Todo text"
116
+ value={text}
117
+ onChange={(e) => setText(e.target.value)}
118
+ />
119
+ <input
120
+ type="number"
121
+ min="1"
122
+ max="10"
123
+ placeholder="Priority (1-10)"
124
+ value={priority}
125
+ onChange={(e) =>
126
+ setPriority(Math.max(1, Math.min(10, Number(e.target.value))))
127
+ }
128
+ />
129
+ <button onClick={addTodo} disabled={!text.trim()}>
130
+ Add Todo
131
+ </button>
132
+ </div>
133
+ <ul className="todo-list">
134
+ {todoList.map((todo) => (
135
+ <li key={todo.id} className={todo.completed ? 'completed' : ''}>
136
+ <input
137
+ type="checkbox"
138
+ checked={todo.completed}
139
+ onChange={() => {
140
+ setTodos((prev) => {
141
+ const next = prev.clone();
142
+
143
+ // Delete the old todo object
144
+ next.delete(todo);
145
+ next.add({ ...todo, completed: !todo.completed });
146
+ return next;
147
+ });
148
+ }}
149
+ />
150
+ <span>{todo.text}</span>
151
+ <span className="priority">P{todo.priority}</span>
152
+ <button onClick={() => deleteTodo(todo)}>Delete</button>
153
+ </li>
154
+ ))}
155
+ </ul>
156
+ </div>
157
+ );
158
+ }
159
+ ```
160
+
161
+ ---
162
+
163
+ ## Express Integration
164
+
165
+ ### Use Case: LRU Cache Middleware
166
+
167
+ ```javascript
168
+ const {DoublyLinkedList} = require('data-structure-typed');
169
+
170
+ class LRUCache {
171
+ constructor(capacity = 100) {
172
+ this.cache = new Map();
173
+ this.order = new DoublyLinkedList();
174
+ this.capacity = capacity;
175
+ }
176
+ get(key) {
177
+ if (!this.cache.has(key))
178
+ return null;
179
+ const { value, node } = this.cache.get(key);
180
+ // Move to end (most recently used)
181
+ this.order.delete(node);
182
+ const newNode = this.order.push(key);
183
+ this.cache.set(key, { value, node: newNode });
184
+ return value;
185
+ }
186
+ set(key, value) {
187
+ if (this.cache.has(key)) {
188
+ this.get(key); // Mark as recently used
189
+ this.cache.get(key).value = value;
190
+ return;
191
+ }
192
+ if (this.cache.size >= this.capacity) {
193
+ const lru = this.order.shift();
194
+ this.cache.delete(lru);
195
+ }
196
+ const node = this.order.push(key);
197
+ this.cache.set(key, { value, node });
198
+ }
199
+ }
200
+
201
+ module.exports = LRUCache;
202
+ ```
203
+
204
+ ```javascript
205
+ // Usage in Express
206
+ const app = express();
207
+ const responseCache = new LRUCache(50);
208
+ app.use((req, res, next) => {
209
+ const cachedResponse = responseCache.get(req.url);
210
+ if (cachedResponse) {
211
+ return res.status(cachedResponse.status).json(cachedResponse.data);
212
+ }
213
+ // Wrap original send to cache response
214
+ const originalSend = res.send;
215
+ res.send = function (data) {
216
+ responseCache.set(req.url, { status: res.statusCode, data });
217
+ return originalSend.call(this, data);
218
+ };
219
+ next();
220
+ });
221
+ app.get('/api/data', (req, res) => {
222
+ res.json({ message: 'Cached response' });
223
+ });
224
+ app.listen(3000);
225
+ ```
226
+
227
+ ### Use Case: Rate Limiting with Deque
228
+
229
+ ```typescript
230
+ import { Deque } from 'data-structure-typed';
231
+
232
+ class RateLimiter {
233
+ private requests = new Map<string, Deque<number>>();
234
+ private limit: number;
235
+ private windowMs: number;
236
+
237
+ constructor(limit: number = 100, windowMs: number = 60000) {
238
+ this.limit = limit;
239
+ this.windowMs = windowMs;
240
+ }
241
+
242
+ isAllowed(clientId: string): boolean {
243
+ const now = Date.now();
244
+
245
+ if (!this.requests.has(clientId)) {
246
+ this.requests.set(clientId, new Deque());
247
+ }
248
+
249
+ const deque = this.requests.get(clientId)!;
250
+
251
+ // Remove old requests outside window
252
+ while (!deque.isEmpty && deque.peekFirst()! < now - this.windowMs) {
253
+ deque.shift();
254
+ }
255
+
256
+ // Check limit
257
+ if (deque.size >= this.limit) {
258
+ return false;
259
+ }
260
+
261
+ // Add new request
262
+ deque.push(now);
263
+ return true;
264
+ }
265
+ }
266
+
267
+ // Usage in Express
268
+ const app = express();
269
+ const limiter = new RateLimiter(10, 60000); // 10 requests per minute
270
+
271
+ app.use((req: Request, res: Response, next: Function) => {
272
+ const clientId = req.ip;
273
+
274
+ if (!limiter.isAllowed(clientId)) {
275
+ return res.status(429).json({ error: 'Too many requests' });
276
+ }
277
+
278
+ next();
279
+ });
280
+
281
+ app.get('/api/data', (req, res) => {
282
+ res.json({ data: 'Your data here' });
283
+ });
284
+ ```
285
+
286
+ ---
287
+
288
+ ## Nest.js Integration
289
+
290
+ ### Use Case: Product Price Index Service
291
+
292
+ ```typescript
293
+ import {
294
+ BadRequestException,
295
+ Injectable,
296
+ NotFoundException,
297
+ } from '@nestjs/common';
298
+
299
+ import { Range, RedBlackTree } from 'data-structure-typed';
300
+
301
+ export interface Product {
302
+ id: string;
303
+ name: string;
304
+ price: number;
305
+ quantity: number;
306
+ category: string;
307
+ lastUpdated?: Date;
308
+ }
309
+
310
+ /** KEY INSIGHT: Use compound keys to solve the problem of "multiple products at the same price" */
311
+ interface CompositeKey {
312
+ price: number;
313
+ productId: string;
314
+ }
315
+
316
+ export type TierName = 'budget' | 'mid-range' | 'premium';
317
+
318
+ /**
319
+ * Product Price Index Service using Red-Black Tree with Composite Keys
320
+ *
321
+ * ⭐ Performance vs Alternatives:
322
+ *
323
+ * Operation | RBTree(this approach) | Array | HashMap + Sort
324
+ * -------------------|-----------------------|-----------|---------------
325
+ * Range Query | O(log n + k) | O(n) | O(k log k)
326
+ * Point Lookup | O(1) | O(1) | O(1)
327
+ * Insert/Update | O(log n) | O(n) | O(log n)
328
+ * Sort by Price | O(n) | O(n log n)| O(n log n)
329
+ * Multiple at Price | ✓ Supported | ✓ | Complex
330
+ *
331
+ * Advantages:
332
+ * - O(1) idToKeyMap lookup + O(log n) tree operations
333
+ * - Automatic ordering without post-sort
334
+ * - Efficient range queries for pricing tiers
335
+ * - Low memory footprint vs duplicate maps
336
+ */
337
+ @Injectable()
338
+ export class ProductPriceIndexService {
339
+ private priceIndex: RedBlackTree<CompositeKey, Product>;
340
+ private idToKeyMap: Map<string, CompositeKey>;
341
+
342
+ constructor() {
343
+ this.priceIndex = new RedBlackTree([], {
344
+ comparator: (a: CompositeKey, b: CompositeKey) => {
345
+ const priceCmp = a.price - b.price;
346
+ if (priceCmp !== 0) return priceCmp;
347
+ return a.productId.localeCompare(b.productId);
348
+ },
349
+ });
350
+ this.idToKeyMap = new Map();
351
+ }
352
+
353
+ /** Time Complexity: O(log n) */
354
+ addProduct(product: Product): Product {
355
+ if (this.idToKeyMap.has(product.id))
356
+ throw new BadRequestException(`Product ${product.id} already exists`);
357
+
358
+ product.lastUpdated = new Date();
359
+
360
+ const key: CompositeKey = {
361
+ price: product.price,
362
+ productId: product.id,
363
+ };
364
+
365
+ this.priceIndex.add(key, product);
366
+ this.idToKeyMap.set(product.id, key);
367
+
368
+ return product;
369
+ }
370
+
371
+ /** Time Complexity: O(log n) */
372
+ updateProduct(productId: string, updates: Partial<Product>): Product {
373
+ const oldKey = this.idToKeyMap.get(productId);
374
+ if (oldKey === undefined)
375
+ throw new NotFoundException(`Product ${productId} not found`);
376
+
377
+ const existing = this.priceIndex.get(oldKey);
378
+ if (!existing)
379
+ throw new NotFoundException(`Product ${productId} not found`);
380
+
381
+ const updated: Product = {
382
+ ...existing,
383
+ ...updates,
384
+ id: existing.id,
385
+ lastUpdated: new Date(),
386
+ };
387
+
388
+ const newPrice = updates.price ?? existing.price;
389
+
390
+ this.priceIndex.delete(oldKey);
391
+ const currentKey: CompositeKey = {
392
+ price: newPrice,
393
+ productId,
394
+ };
395
+ this.priceIndex.set(currentKey, updated);
396
+ this.idToKeyMap.set(productId, currentKey);
397
+
398
+ return updated;
399
+ }
400
+
401
+ /** Time Complexity: O(1) */
402
+ getProductById(productId: string): Product {
403
+ const key = this.idToKeyMap.get(productId);
404
+
405
+ if (key === undefined)
406
+ throw new NotFoundException(`Product ${productId} not found`);
407
+
408
+ return this.priceIndex.get(key)!;
409
+ }
410
+
411
+ /** Time Complexity: O(log n + k) */
412
+ getProductsByPriceRange(minPrice: number, maxPrice: number): Product[] {
413
+ const range = new Range(
414
+ { price: minPrice, productId: '' },
415
+ { price: maxPrice, productId: '\uffff' },
416
+ true, // includeLow
417
+ true, // includeHigh
418
+ );
419
+
420
+ const keys = this.priceIndex.rangeSearch(range, (n) => n.key);
421
+ return keys.map((key) => this.priceIndex.get(key)!);
422
+ }
423
+
424
+ /** Time Complexity: O(log n) */
425
+ getHighestPricedProductWithinBudget(maxBudget: number): Product | null {
426
+ const key: CompositeKey = {
427
+ price: maxBudget,
428
+ productId: '\uffff',
429
+ };
430
+ const floorKey = this.priceIndex.floor(key);
431
+ return floorKey ? this.priceIndex.get(floorKey)! : null;
432
+ }
433
+
434
+ /** Time O(log n) */
435
+ getCheapestProductAbovePrice(minPrice: number): Product | null {
436
+ const key: CompositeKey = {
437
+ price: minPrice,
438
+ productId: '\uffff',
439
+ };
440
+ const higherKey = this.priceIndex.higher(key);
441
+ return higherKey ? this.priceIndex.get(higherKey)! : null;
442
+ }
443
+
444
+ /** Time Complexity: O(log n + k) */
445
+ getProductsByTier(tierName: TierName): Product[] {
446
+ const tiers = {
447
+ budget: [0, 50],
448
+ 'mid-range': [50, 200],
449
+ premium: [200, Infinity],
450
+ };
451
+
452
+ const [min, max] = tiers[tierName];
453
+ return this.getProductsByPriceRange(min, max);
454
+ }
455
+
456
+ /** Time Complexity: O(log n + k + m) */
457
+ getProductsByPriceAndCategory(
458
+ minPrice: number,
459
+ maxPrice: number,
460
+ category: string,
461
+ ): Product[] {
462
+ const priceRangeProducts = this.getProductsByPriceRange(minPrice, maxPrice);
463
+ return priceRangeProducts.filter(
464
+ (p) => p.category.toLowerCase() === category.toLowerCase(),
465
+ );
466
+ }
467
+
468
+ /** Time Complexity: O((log n + k) * log n) */
469
+ applyDiscountToRange(
470
+ minPrice: number,
471
+ maxPrice: number,
472
+ discountPercent: number,
473
+ ): Product[] {
474
+ const products = this.getProductsByPriceRange(minPrice, maxPrice);
475
+ const updated: Product[] = [];
476
+
477
+ for (const product of products) {
478
+ const newPrice = product.price * (1 - discountPercent / 100);
479
+ const updatedProduct = this.updateProduct(product.id, {
480
+ price: newPrice,
481
+ });
482
+ updated.push(updatedProduct);
483
+ }
484
+
485
+ return updated;
486
+ }
487
+
488
+ /** Time Complexity: O(log n) */
489
+ deleteProduct(productId: string): void {
490
+ const key = this.idToKeyMap.get(productId);
491
+
492
+ if (key === undefined)
493
+ throw new NotFoundException(`Product ${productId} not found`);
494
+
495
+ this.priceIndex.delete(key);
496
+ this.idToKeyMap.delete(productId);
497
+ }
498
+
499
+ /** Time Complexity: O(n) */
500
+ getStatistics(): {
501
+ totalProducts: number;
502
+ priceRange: { min: number; max: number };
503
+ averagePrice: number;
504
+ totalValue: number;
505
+ } {
506
+ if (this.idToKeyMap.size === 0) {
507
+ return {
508
+ totalProducts: 0,
509
+ priceRange: { min: 0, max: 0 },
510
+ averagePrice: 0,
511
+ totalValue: 0,
512
+ };
513
+ }
514
+
515
+ let minPrice = Infinity;
516
+ let maxPrice = -Infinity;
517
+ let totalValue = 0;
518
+ let totalProducts = 0;
519
+
520
+ let entry = this.priceIndex.getLeftMost((node) => node);
521
+
522
+ while (entry) {
523
+ const product = this.priceIndex.get(entry.key);
524
+ if (product) {
525
+ minPrice = Math.min(minPrice, product.price);
526
+ maxPrice = Math.max(maxPrice, product.price);
527
+ totalValue += product.price * product.quantity;
528
+ totalProducts += product.quantity;
529
+ }
530
+
531
+ entry = this.priceIndex.higher(entry.key, (node) => node);
532
+ }
533
+
534
+ return {
535
+ totalProducts: totalProducts,
536
+ priceRange: { min: minPrice, max: maxPrice },
537
+ averagePrice: totalValue / totalProducts,
538
+ totalValue,
539
+ };
540
+ }
541
+
542
+ /** Time Complexity: O(n) */
543
+ getAllProductsSortedByPrice(): Product[] {
544
+ const products: Product[] = [];
545
+ let curNode = this.priceIndex.getLeftMost((node) => node);
546
+
547
+ while (curNode) {
548
+ if (curNode.key) products.push(this.priceIndex.get(curNode.key)!);
549
+ curNode = this.priceIndex.higher(curNode.key, (node) => node);
550
+ }
551
+
552
+ return products;
553
+ }
554
+
555
+ /** O(1) */
556
+ getProductCount(): number {
557
+ return this.idToKeyMap.size;
558
+ }
559
+
560
+ /** O(1) */
561
+ hasProduct(productId: string): boolean {
562
+ return this.idToKeyMap.has(productId);
563
+ }
564
+
565
+ /** O(n) */
566
+ getAllProductIds(): string[] {
567
+ return [...this.idToKeyMap.keys()];
568
+ }
569
+ }
570
+
571
+ ```
572
+
573
+ ### Use Case: Task Queue Controller
574
+
575
+ ```typescript
576
+ import { Controller, Post, Body, Get } from '@nestjs/common';
577
+ import { MaxPriorityQueue } from 'data-structure-typed';
578
+
579
+ export interface QueuedTask {
580
+ id: string;
581
+ action: string;
582
+ priority: number;
583
+ createdAt: Date;
584
+ }
585
+
586
+ @Controller('tasks')
587
+ export class TaskController {
588
+ private taskQueue = new MaxPriorityQueue<QueuedTask>([], {
589
+ comparator: (a, b) => a.priority - b.priority,
590
+ });
591
+
592
+ @Post('add')
593
+ addTask(@Body() task: QueuedTask): { success: boolean; queueSize: number } {
594
+ this.taskQueue.add(task);
595
+ return {
596
+ success: true,
597
+ queueSize: this.taskQueue.size,
598
+ };
599
+ }
600
+
601
+ @Post('process')
602
+ processNext(): { success: boolean; task: QueuedTask | null } {
603
+ const task = this.taskQueue.poll();
604
+ return {
605
+ success: !!task,
606
+ task: task || null,
607
+ };
608
+ }
609
+
610
+ @Get('queue-size')
611
+ getQueueSize(): { size: number } {
612
+ return { size: this.taskQueue.size };
613
+ }
614
+ }
615
+ ```
616
+
617
+ ---
618
+
619
+ ## TypeScript Configuration
620
+
621
+ ### tsconfig.json for data-structure-typed
622
+
623
+ ```json
624
+ {
625
+ "compilerOptions": {
626
+ "target": "ES2020",
627
+ "module": "ES2020",
628
+ "lib": ["ES2020", "DOM"],
629
+ "strict": true,
630
+ "esModuleInterop": true,
631
+ "skipLibCheck": true,
632
+ "forceConsistentCasingInFileNames": true,
633
+ "resolveJsonModule": true,
634
+ "declaration": true,
635
+ "declarationMap": true,
636
+ "sourceMap": true
637
+ }
638
+ }
639
+ ```
640
+
641
+ ### Package.json Setup
642
+
643
+ ```json
644
+ {
645
+ "dependencies": {
646
+ "data-structure-typed": "^latest"
647
+ },
648
+ "devDependencies": {
649
+ "typescript": "^5.0.0",
650
+ "@types/node": "^latest"
651
+ }
652
+ }
653
+ ```
654
+
655
+ ---
656
+
657
+ ## Import Patterns
658
+
659
+ ### All Structures
660
+
661
+ ```typescript
662
+ import {
663
+ // Trees
664
+ BST,
665
+ AVLTree,
666
+ RedBlackTree,
667
+ BSTNode,
668
+ TreeMultiMap,
669
+
670
+ // Linear
671
+ Stack,
672
+ Queue,
673
+ Deque,
674
+ LinkedList,
675
+ SinglyLinkedList,
676
+ DoublyLinkedList,
677
+
678
+ // Heap
679
+ Heap,
680
+ MinHeap,
681
+ MaxHeap,
682
+ MinPriorityQueue,
683
+ MaxPriorityQueue,
684
+
685
+ // Special
686
+ Trie,
687
+ DirectedGraph,
688
+ UndirectedGraph,
689
+
690
+ // Utilities
691
+ SegmentTree,
692
+ FenwickTree
693
+ } from 'data-structure-typed';
694
+ ```
695
+
696
+ ### Module Systems
697
+
698
+ ```js
699
+ // ES Module (ESM)
700
+ import { RedBlackTree } from 'data-structure-typed';
701
+
702
+ // CommonJS
703
+ const { RedBlackTree } = require('data-structure-typed');
704
+
705
+ // TypeScript with full typing
706
+ import { RedBlackTree } from 'data-structure-typed/dist/esm/red-black-tree';
707
+
708
+ // CDN (for browsers)
709
+ <script src="https://cdn.jsdelivr.net/npm/data-structure-typed/dist/umd/data-structure-typed.min.js"></script>
710
+ <script>
711
+ const tree = new DataStructureTyped.RedBlackTree();
712
+ </script>
713
+ ```
714
+
715
+ ---
716
+
717
+ ## Common Integration Patterns
718
+
719
+ ### Pattern 1: Dependency Injection (Nest.js)
720
+
721
+ ```typescript
722
+ import { Module } from '@nestjs/common';
723
+ import { ProductInventoryService } from './product-inventory.service';
724
+
725
+ @Module({
726
+ providers: [ProductInventoryService],
727
+ exports: [ProductInventoryService]
728
+ })
729
+ export class ProductInventoryModule {}
730
+
731
+ // Use in other services
732
+ @Injectable()
733
+ export class OutherService {
734
+ constructor(private inventoryService: ProductInventoryService) {}
735
+
736
+ async addProduct(product: Product): Promise<void> {
737
+ this.inventoryService.addProduct(product);
738
+ }
739
+ }
740
+ ```
741
+
742
+ ### Pattern 2: React Hooks
743
+
744
+ ```tsx
745
+ import {useCallback, useRef, useState} from 'react';
746
+ import {RedBlackTree} from 'data-structure-typed';
747
+
748
+ function useSortedList<T>(initialData: T[] = []) {
749
+ const treeRef = useRef(new RedBlackTree<number, T>(initialData));
750
+ const [, setUpdateTrigger] = useState({});
751
+
752
+ const add = useCallback((index: number, item: T) => {
753
+ treeRef.current.set(index, item);
754
+ setUpdateTrigger({});
755
+ }, []);
756
+
757
+ const remove = useCallback((index: number) => {
758
+ treeRef.current.delete(index);
759
+ setUpdateTrigger({});
760
+ }, []);
761
+
762
+ const getAll = useCallback(() => {
763
+ return [...treeRef.current.values()];
764
+ }, []);
765
+
766
+ return {add, remove, getAll};
767
+ }
768
+
769
+ // Usage
770
+ function MyComponent() {
771
+ const {add, remove, getAll} = useSortedList<string>([]);
772
+
773
+ return (
774
+ <div>
775
+ <button onClick={() => add(1, 'Item 1')}>Add Item</button>
776
+ <ul>
777
+ {getAll().map((item, i) => (
778
+ <li key={i} onClick={() => remove(i)}>{item}</li>
779
+ ))}
780
+ </ul>
781
+ </div>
782
+ );
783
+ }
784
+
785
+ export default MyComponent;
786
+ ```
787
+
788
+ ---
789
+
790
+ ## Troubleshooting
791
+
792
+ ### Issue: Import Error
793
+
794
+ ```typescript
795
+ // ❌ Wrong
796
+ import RedBlackTree from 'data-structure-typed';
797
+
798
+ // ✅ Correct
799
+ import { RedBlackTree } from 'data-structure-typed';
800
+ ```
801
+
802
+ ### Issue: Type Not Found
803
+
804
+ ```shell
805
+ // Make sure TypeScript configuration is correct
806
+ // and you have the latest type definitions
807
+ npm update data-structure-typed
808
+ ```
809
+
810
+ ### Issue: Performance in Development
811
+
812
+ ```shell
813
+ // Development mode is slower due to hot reload
814
+ // Use production build for benchmarking:
815
+ npm run build
816
+ NODE_ENV=production node your-app.js
817
+ ```
818
+
819
+ ---
820
+
821
+ **Need more examples?** Check [GUIDES.md](/guide/guides.md) for more patterns.
822
+
823
+ **Performance questions?** See [PERFORMANCE.md](/guide/performance.md).