data-structure-typed 2.5.1 → 2.5.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 (172) hide show
  1. package/CHANGELOG.md +3 -1
  2. package/README.md +75 -17
  3. package/dist/cjs/binary-tree.cjs +2723 -139
  4. package/dist/cjs/graph.cjs +192 -6
  5. package/dist/cjs/hash.cjs +63 -15
  6. package/dist/cjs/heap.cjs +93 -31
  7. package/dist/cjs/index.cjs +3514 -379
  8. package/dist/cjs/linked-list.cjs +237 -31
  9. package/dist/cjs/matrix.cjs +47 -9
  10. package/dist/cjs/priority-queue.cjs +92 -30
  11. package/dist/cjs/queue.cjs +176 -2
  12. package/dist/cjs/stack.cjs +48 -2
  13. package/dist/cjs/trie.cjs +78 -28
  14. package/dist/cjs-legacy/binary-tree.cjs +2725 -136
  15. package/dist/cjs-legacy/graph.cjs +192 -6
  16. package/dist/cjs-legacy/hash.cjs +63 -15
  17. package/dist/cjs-legacy/heap.cjs +93 -31
  18. package/dist/cjs-legacy/index.cjs +3389 -249
  19. package/dist/cjs-legacy/linked-list.cjs +237 -31
  20. package/dist/cjs-legacy/matrix.cjs +47 -9
  21. package/dist/cjs-legacy/priority-queue.cjs +92 -30
  22. package/dist/cjs-legacy/queue.cjs +176 -2
  23. package/dist/cjs-legacy/stack.cjs +48 -2
  24. package/dist/cjs-legacy/trie.cjs +78 -28
  25. package/dist/esm/binary-tree.mjs +2723 -139
  26. package/dist/esm/graph.mjs +192 -6
  27. package/dist/esm/hash.mjs +63 -15
  28. package/dist/esm/heap.mjs +93 -31
  29. package/dist/esm/index.mjs +3514 -380
  30. package/dist/esm/linked-list.mjs +237 -31
  31. package/dist/esm/matrix.mjs +47 -9
  32. package/dist/esm/priority-queue.mjs +92 -30
  33. package/dist/esm/queue.mjs +176 -2
  34. package/dist/esm/stack.mjs +48 -2
  35. package/dist/esm/trie.mjs +78 -28
  36. package/dist/esm-legacy/binary-tree.mjs +2725 -136
  37. package/dist/esm-legacy/graph.mjs +192 -6
  38. package/dist/esm-legacy/hash.mjs +63 -15
  39. package/dist/esm-legacy/heap.mjs +93 -31
  40. package/dist/esm-legacy/index.mjs +3389 -250
  41. package/dist/esm-legacy/linked-list.mjs +237 -31
  42. package/dist/esm-legacy/matrix.mjs +47 -9
  43. package/dist/esm-legacy/priority-queue.mjs +92 -30
  44. package/dist/esm-legacy/queue.mjs +176 -2
  45. package/dist/esm-legacy/stack.mjs +48 -2
  46. package/dist/esm-legacy/trie.mjs +78 -28
  47. package/dist/types/common/error.d.ts +9 -0
  48. package/dist/types/common/index.d.ts +1 -1
  49. package/dist/types/data-structures/binary-tree/avl-tree.d.ts +48 -0
  50. package/dist/types/data-structures/binary-tree/binary-indexed-tree.d.ts +56 -0
  51. package/dist/types/data-structures/binary-tree/binary-tree.d.ts +102 -2
  52. package/dist/types/data-structures/binary-tree/bst.d.ts +195 -0
  53. package/dist/types/data-structures/binary-tree/red-black-tree.d.ts +76 -0
  54. package/dist/types/data-structures/binary-tree/segment-tree.d.ts +24 -0
  55. package/dist/types/data-structures/binary-tree/tree-map.d.ts +528 -0
  56. package/dist/types/data-structures/binary-tree/tree-multi-map.d.ts +531 -6
  57. package/dist/types/data-structures/binary-tree/tree-multi-set.d.ts +435 -6
  58. package/dist/types/data-structures/binary-tree/tree-set.d.ts +505 -0
  59. package/dist/types/data-structures/graph/directed-graph.d.ts +40 -0
  60. package/dist/types/data-structures/graph/undirected-graph.d.ts +36 -0
  61. package/dist/types/data-structures/hash/hash-map.d.ts +44 -0
  62. package/dist/types/data-structures/heap/heap.d.ts +56 -0
  63. package/dist/types/data-structures/linked-list/doubly-linked-list.d.ts +68 -0
  64. package/dist/types/data-structures/linked-list/singly-linked-list.d.ts +60 -0
  65. package/dist/types/data-structures/linked-list/skip-linked-list.d.ts +72 -0
  66. package/dist/types/data-structures/matrix/matrix.d.ts +32 -0
  67. package/dist/types/data-structures/queue/deque.d.ts +60 -0
  68. package/dist/types/data-structures/queue/queue.d.ts +48 -0
  69. package/dist/types/data-structures/stack/stack.d.ts +40 -0
  70. package/dist/types/data-structures/trie/trie.d.ts +48 -0
  71. package/dist/types/types/data-structures/binary-tree/bst.d.ts +1 -0
  72. package/dist/types/types/data-structures/binary-tree/tree-map.d.ts +5 -0
  73. package/dist/types/types/data-structures/binary-tree/tree-multi-set.d.ts +4 -0
  74. package/dist/types/types/data-structures/binary-tree/tree-set.d.ts +4 -0
  75. package/dist/umd/data-structure-typed.js +3404 -265
  76. package/dist/umd/data-structure-typed.min.js +5 -5
  77. package/docs-site-docusaurus/docs/api/classes/AVLTree.md +650 -136
  78. package/docs-site-docusaurus/docs/api/classes/AVLTreeNode.md +11 -11
  79. package/docs-site-docusaurus/docs/api/classes/AbstractGraph.md +71 -71
  80. package/docs-site-docusaurus/docs/api/classes/BST.md +591 -129
  81. package/docs-site-docusaurus/docs/api/classes/BSTNode.md +13 -13
  82. package/docs-site-docusaurus/docs/api/classes/BinaryIndexedTree.md +15 -15
  83. package/docs-site-docusaurus/docs/api/classes/BinaryTree.md +107 -107
  84. package/docs-site-docusaurus/docs/api/classes/BinaryTreeNode.md +13 -13
  85. package/docs-site-docusaurus/docs/api/classes/Deque.md +82 -82
  86. package/docs-site-docusaurus/docs/api/classes/DirectedGraph.md +82 -82
  87. package/docs-site-docusaurus/docs/api/classes/DoublyLinkedList.md +74 -74
  88. package/docs-site-docusaurus/docs/api/classes/DoublyLinkedListNode.md +8 -8
  89. package/docs-site-docusaurus/docs/api/classes/FibonacciHeap.md +9 -9
  90. package/docs-site-docusaurus/docs/api/classes/FibonacciHeapNode.md +1 -1
  91. package/docs-site-docusaurus/docs/api/classes/HashMap.md +47 -47
  92. package/docs-site-docusaurus/docs/api/classes/Heap.md +45 -45
  93. package/docs-site-docusaurus/docs/api/classes/IterableElementBase.md +25 -25
  94. package/docs-site-docusaurus/docs/api/classes/IterableEntryBase.md +33 -33
  95. package/docs-site-docusaurus/docs/api/classes/LinearBase.md +50 -50
  96. package/docs-site-docusaurus/docs/api/classes/LinearLinkedBase.md +55 -55
  97. package/docs-site-docusaurus/docs/api/classes/LinkedHashMap.md +49 -49
  98. package/docs-site-docusaurus/docs/api/classes/LinkedListNode.md +6 -6
  99. package/docs-site-docusaurus/docs/api/classes/LinkedListQueue.md +78 -78
  100. package/docs-site-docusaurus/docs/api/classes/MapGraph.md +82 -82
  101. package/docs-site-docusaurus/docs/api/classes/Matrix.md +31 -31
  102. package/docs-site-docusaurus/docs/api/classes/MaxHeap.md +45 -45
  103. package/docs-site-docusaurus/docs/api/classes/MaxPriorityQueue.md +45 -45
  104. package/docs-site-docusaurus/docs/api/classes/MinHeap.md +45 -45
  105. package/docs-site-docusaurus/docs/api/classes/MinPriorityQueue.md +45 -45
  106. package/docs-site-docusaurus/docs/api/classes/Navigator.md +5 -5
  107. package/docs-site-docusaurus/docs/api/classes/PriorityQueue.md +44 -44
  108. package/docs-site-docusaurus/docs/api/classes/Queue.md +60 -60
  109. package/docs-site-docusaurus/docs/api/classes/RedBlackTree.md +660 -146
  110. package/docs-site-docusaurus/docs/api/classes/SegmentTree.md +10 -10
  111. package/docs-site-docusaurus/docs/api/classes/SinglyLinkedList.md +78 -78
  112. package/docs-site-docusaurus/docs/api/classes/SinglyLinkedListNode.md +6 -6
  113. package/docs-site-docusaurus/docs/api/classes/SkipList.md +44 -44
  114. package/docs-site-docusaurus/docs/api/classes/Stack.md +39 -39
  115. package/docs-site-docusaurus/docs/api/classes/TreeMap.md +165 -33
  116. package/docs-site-docusaurus/docs/api/classes/TreeMultiMap.md +162 -46
  117. package/docs-site-docusaurus/docs/api/classes/TreeSet.md +161 -32
  118. package/docs-site-docusaurus/docs/api/classes/Trie.md +47 -47
  119. package/docs-site-docusaurus/docs/api/classes/TrieNode.md +8 -8
  120. package/docs-site-docusaurus/docs/api/classes/UndirectedGraph.md +81 -81
  121. package/docs-site-docusaurus/docs/guide/architecture.md +2 -0
  122. package/docs-site-docusaurus/docs/guide/concepts.md +32 -1
  123. package/docs-site-docusaurus/docs/guide/faq.md +180 -0
  124. package/docs-site-docusaurus/docs/guide/guides.md +40 -54
  125. package/docs-site-docusaurus/docs/guide/installation.md +2 -0
  126. package/docs-site-docusaurus/docs/guide/integrations.md +2 -0
  127. package/docs-site-docusaurus/docs/guide/overview.md +7 -0
  128. package/docs-site-docusaurus/docs/guide/performance.md +2 -0
  129. package/docs-site-docusaurus/docs/guide/quick-start.md +31 -0
  130. package/docs-site-docusaurus/docs/guide/use-cases/_category_.json +6 -0
  131. package/docs-site-docusaurus/docs/guide/use-cases/array-sort-alternative.md +158 -0
  132. package/docs-site-docusaurus/docs/guide/use-cases/heap-vs-sorting.md +92 -0
  133. package/docs-site-docusaurus/docs/guide/use-cases/map-vs-treemap.md +151 -0
  134. package/docs-site-docusaurus/docs/guide/use-cases/priority-queue-typescript.md +113 -0
  135. package/docs-site-docusaurus/docs/guide/use-cases/treemap-javascript.md +151 -0
  136. package/docs-site-docusaurus/docusaurus.config.ts +1 -1
  137. package/docs-site-docusaurus/src/pages/index.tsx +51 -2
  138. package/docs-site-docusaurus/static/llms.txt +37 -0
  139. package/llms.txt +37 -0
  140. package/package.json +64 -56
  141. package/src/common/error.ts +19 -1
  142. package/src/common/index.ts +1 -1
  143. package/src/data-structures/base/iterable-element-base.ts +3 -2
  144. package/src/data-structures/binary-tree/avl-tree.ts +47 -0
  145. package/src/data-structures/binary-tree/binary-indexed-tree.ts +46 -4
  146. package/src/data-structures/binary-tree/binary-tree.ts +79 -4
  147. package/src/data-structures/binary-tree/bst.ts +441 -6
  148. package/src/data-structures/binary-tree/red-black-tree.ts +73 -0
  149. package/src/data-structures/binary-tree/segment-tree.ts +18 -0
  150. package/src/data-structures/binary-tree/tree-map.ts +434 -9
  151. package/src/data-structures/binary-tree/tree-multi-map.ts +426 -5
  152. package/src/data-structures/binary-tree/tree-multi-set.ts +350 -6
  153. package/src/data-structures/binary-tree/tree-set.ts +410 -8
  154. package/src/data-structures/graph/abstract-graph.ts +2 -2
  155. package/src/data-structures/graph/directed-graph.ts +30 -0
  156. package/src/data-structures/graph/undirected-graph.ts +27 -0
  157. package/src/data-structures/hash/hash-map.ts +35 -4
  158. package/src/data-structures/heap/heap.ts +46 -4
  159. package/src/data-structures/heap/max-heap.ts +2 -2
  160. package/src/data-structures/linked-list/doubly-linked-list.ts +51 -0
  161. package/src/data-structures/linked-list/singly-linked-list.ts +45 -0
  162. package/src/data-structures/linked-list/skip-linked-list.ts +59 -5
  163. package/src/data-structures/matrix/matrix.ts +33 -9
  164. package/src/data-structures/priority-queue/max-priority-queue.ts +2 -2
  165. package/src/data-structures/queue/deque.ts +45 -0
  166. package/src/data-structures/queue/queue.ts +36 -0
  167. package/src/data-structures/stack/stack.ts +30 -0
  168. package/src/data-structures/trie/trie.ts +38 -2
  169. package/src/types/data-structures/binary-tree/bst.ts +1 -0
  170. package/src/types/data-structures/binary-tree/tree-map.ts +6 -0
  171. package/src/types/data-structures/binary-tree/tree-multi-set.ts +5 -0
  172. package/src/types/data-structures/binary-tree/tree-set.ts +5 -0
@@ -0,0 +1,158 @@
1
+ ---
2
+ title: When Array + Sort Becomes Too Slow
3
+ description: Stop re-sorting arrays after every insert. Use TreeMap, TreeSet, or Heap for O(log n) ordered operations in JavaScript and TypeScript.
4
+ keywords: [javascript sorted insert, array sort performance, sorted array alternative, binary search insert javascript, ordered collection typescript]
5
+ sidebar_label: Array + Sort Alternatives
6
+ ---
7
+
8
+ # When Array + Sort Becomes Too Slow
9
+
10
+ A common pattern in JavaScript:
11
+
12
+ ```typescript
13
+ const items: number[] = [];
14
+
15
+ function addSorted(value: number) {
16
+ items.push(value);
17
+ items.sort((a, b) => a - b); // O(n log n) every time!
18
+ }
19
+ ```
20
+
21
+ This works fine for 100 elements. At 10,000, it's noticeably slow. At 100,000, it's a bottleneck.
22
+
23
+ ## Why This Is Slow
24
+
25
+ | Elements | Array push + sort | Tree insert |
26
+ |----------|------------------|-------------|
27
+ | 100 | ~0.01ms | ~0.01ms |
28
+ | 10,000 | ~5ms | ~0.1ms |
29
+ | 100,000 | ~80ms | ~0.2ms |
30
+ | 1,000,000 | ~1200ms | ~0.5ms |
31
+
32
+ Array.sort is O(n log n). Tree insert is O(log n). The gap grows with data size.
33
+
34
+ ## Choose the Right Alternative
35
+
36
+ ### Need sorted key-value pairs → TreeMap
37
+
38
+ ```typescript
39
+ import { TreeMap } from 'data-structure-typed';
40
+
41
+ const prices = new TreeMap<string, number>();
42
+ prices.set('apple', 1.2);
43
+ prices.set('banana', 0.5);
44
+ prices.set('cherry', 2.5);
45
+
46
+ // Always sorted by key
47
+ for (const [fruit, price] of prices) {
48
+ console.log(fruit, price);
49
+ }
50
+ // apple 1.2, banana 0.5, cherry 2.5
51
+
52
+ // Find nearest
53
+ prices.floor('blueberry'); // ['banana', 0.5]
54
+ ```
55
+
56
+ ### Need sorted unique values → TreeSet
57
+
58
+ ```typescript
59
+ import { TreeSet } from 'data-structure-typed';
60
+
61
+ const uniqueScores = new TreeSet<number>();
62
+ uniqueScores.add(85);
63
+ uniqueScores.add(92);
64
+ uniqueScores.add(78);
65
+ uniqueScores.add(85); // duplicate ignored
66
+
67
+ [...uniqueScores]; // [78, 85, 92] — sorted, unique
68
+ ```
69
+
70
+ ### Only need min or max → Heap
71
+
72
+ ```typescript
73
+ import { MinHeap } from 'data-structure-typed';
74
+
75
+ const heap = new MinHeap<number>();
76
+ heap.add(5);
77
+ heap.add(2);
78
+ heap.add(8);
79
+
80
+ heap.peek(); // 2 — O(1)
81
+ heap.poll(); // 2 — O(log n), removes and returns min
82
+ ```
83
+
84
+ Heap is lighter than TreeMap when you only need the top element.
85
+
86
+ ## Decision Guide
87
+
88
+ ```
89
+ Do you need...
90
+ ├── Only the min or max? → Heap / MinHeap / MaxHeap
91
+ ├── Sorted iteration of all elements?
92
+ │ ├── Key-value pairs? → TreeMap
93
+ │ └── Values only? → TreeSet
94
+ ├── Floor / ceiling / range queries? → TreeMap / TreeSet
95
+ ├── Rank queries (kth element)? → TreeMap/TreeSet with enableOrderStatistic
96
+ └── Just fast lookup by key? → HashMap (or native Map)
97
+ ```
98
+
99
+ ## Before and After
100
+
101
+ ### Task queue (before)
102
+ ```typescript
103
+ // ❌ O(n log n) per insert
104
+ const tasks: { priority: number; name: string }[] = [];
105
+ tasks.push({ priority: 3, name: 'email' });
106
+ tasks.push({ priority: 1, name: 'bugfix' });
107
+ tasks.sort((a, b) => a.priority - b.priority);
108
+ const next = tasks.shift(); // O(n) shift
109
+ ```
110
+
111
+ ### Task queue (after)
112
+ ```typescript
113
+ // ✅ O(log n) per insert, O(log n) per poll
114
+ import { MinPriorityQueue } from 'data-structure-typed';
115
+
116
+ const tasks = new MinPriorityQueue<{ priority: number; name: string }>({
117
+ comparator: (a, b) => a.priority - b.priority
118
+ });
119
+ tasks.add({ priority: 3, name: 'email' });
120
+ tasks.add({ priority: 1, name: 'bugfix' });
121
+ const next = tasks.poll(); // { priority: 1, name: 'bugfix' }
122
+ ```
123
+
124
+ ### Leaderboard (before)
125
+ ```typescript
126
+ // ❌ Re-sort after every score update
127
+ const scores: [string, number][] = [];
128
+ scores.push(['Alice', 100]);
129
+ scores.push(['Bob', 250]);
130
+ scores.sort((a, b) => b[1] - a[1]);
131
+ const top3 = scores.slice(0, 3); // O(n log n) + O(k)
132
+ ```
133
+
134
+ ### Leaderboard (after)
135
+ ```typescript
136
+ // ✅ O(log n) insert, O(log n + k) for top-k
137
+ import { TreeMap } from 'data-structure-typed';
138
+
139
+ const board = new TreeMap<number, string>(
140
+ [[100, 'Alice'], [250, 'Bob']],
141
+ { comparator: (a, b) => b - a, enableOrderStatistic: true }
142
+ );
143
+ board.rangeByRank(0, 2); // Top 3 in O(log n + k)
144
+ ```
145
+
146
+ ## Complexity Cheat Sheet
147
+
148
+ | Operation | Array + sort | TreeMap/TreeSet | Heap |
149
+ |-----------|-------------|----------------|------|
150
+ | Insert (maintain order) | O(n log n) | O(log n) | O(log n) |
151
+ | Get min/max | O(1) | O(log n) | O(1) |
152
+ | Delete min/max | O(n) | O(log n) | O(log n) |
153
+ | Find by key | O(log n) | O(log n) | O(n) |
154
+ | Floor/Ceiling | O(log n) | O(log n) | ❌ |
155
+ | Range query | O(log n + k) | O(log n + k) | ❌ |
156
+ | Sorted iteration | O(1)* | O(n) | O(n log n) |
157
+
158
+ *Array is already sorted, so iteration is free — but maintaining that sort is expensive.
@@ -0,0 +1,92 @@
1
+ ---
2
+ title: Heap vs Sorting an Array — When to Use Which
3
+ description: Compare Heap and Array.sort for priority queues, top-k, and streaming data in JavaScript/TypeScript. Performance analysis and code examples.
4
+ keywords: [heap vs sort, array sort performance, priority queue vs sort, top k javascript, heap javascript, when to use heap]
5
+ sidebar_label: Heap vs Sorting
6
+ ---
7
+
8
+ # Heap vs Sorting an Array
9
+
10
+ Both can give you ordered data. But they're optimized for different access patterns.
11
+
12
+ ## Quick Answer
13
+
14
+ - **Need all elements sorted** → sort the array once
15
+ - **Need only the min/max repeatedly** → use a Heap
16
+ - **Streaming data (elements arrive over time)** → use a Heap
17
+ - **Static data, one-time sort** → use Array.sort
18
+
19
+ ## Performance Comparison
20
+
21
+ | Operation | Array.sort | Heap |
22
+ |-----------|-----------|------|
23
+ | Sort all elements | O(n log n) | O(n log n) |
24
+ | Insert 1 element (keep sorted) | O(n log n) or O(n)* | O(log n) |
25
+ | Get min/max | O(1) | O(1) |
26
+ | Remove min/max | O(n) | O(log n) |
27
+ | Get top-k from n elements | O(n log n) | O(n log k) |
28
+
29
+ *O(n) if you binary-search + splice; O(n log n) if you push + re-sort.
30
+
31
+ ## Example: Top-K Scores
32
+
33
+ ### Array approach
34
+ ```typescript
35
+ // ❌ Sort everything, take first k
36
+ function topK_array(scores: number[], k: number): number[] {
37
+ return scores.sort((a, b) => b - a).slice(0, k);
38
+ // O(n log n) — sorts ALL elements even if k is small
39
+ }
40
+ ```
41
+
42
+ ### Heap approach
43
+ ```typescript
44
+ import { MinHeap } from 'data-structure-typed';
45
+
46
+ // ✅ Only maintain k elements in the heap
47
+ function topK_heap(scores: number[], k: number): number[] {
48
+ const heap = new MinHeap<number>();
49
+ for (const score of scores) {
50
+ heap.add(score);
51
+ if (heap.size > k) heap.poll();
52
+ }
53
+ return heap.toArray().sort((a, b) => b - a);
54
+ // O(n log k) — much faster when k << n
55
+ }
56
+ ```
57
+
58
+ For 1,000,000 elements with k=10: array sorts all 1M elements. Heap only maintains 10.
59
+
60
+ ## Example: Streaming Data
61
+
62
+ ```typescript
63
+ import { MinHeap } from 'data-structure-typed';
64
+
65
+ // New scores arrive continuously
66
+ const liveScores = new MinHeap<number>();
67
+
68
+ // Each insert: O(log n)
69
+ liveScores.add(85);
70
+ liveScores.add(92);
71
+ liveScores.add(78);
72
+
73
+ // Current lowest: O(1)
74
+ liveScores.peek(); // 78
75
+
76
+ // Process lowest: O(log n)
77
+ liveScores.poll(); // 78
78
+ ```
79
+
80
+ With an array, you'd re-sort after every insert — O(n log n) each time.
81
+
82
+ ## When to Use Each
83
+
84
+ | Scenario | Use Array.sort | Use Heap |
85
+ |----------|---------------|----------|
86
+ | One-time sort of static data | ✅ | ❌ |
87
+ | Repeated insert + get min/max | ❌ | ✅ |
88
+ | Top-k from large dataset | ❌ (k << n) | ✅ |
89
+ | Streaming / real-time data | ❌ | ✅ |
90
+ | Need sorted iteration of ALL elements | ✅ | ❌ |
91
+ | Dijkstra / A* algorithm | ❌ | ✅ |
92
+ | Simple, small dataset (< 100) | ✅ | Either |
@@ -0,0 +1,151 @@
1
+ ---
2
+ title: Map vs TreeMap — When Native Map Isn't Enough
3
+ description: Compare JavaScript's native Map with TreeMap for sorted collections, range queries, and ordered iteration. Code examples and performance analysis.
4
+ keywords: [map vs treemap, javascript map alternative, sorted map javascript, ordered map typescript, treemap performance, when to use treemap]
5
+ sidebar_label: Map vs TreeMap
6
+ ---
7
+
8
+ # Map vs TreeMap
9
+
10
+ JavaScript's `Map` is excellent for key-value lookup. But it has no concept of order, range, or proximity. When you need those, use `TreeMap`.
11
+
12
+ ## Feature Comparison
13
+
14
+ | Feature | Map | TreeMap |
15
+ |---------|-----|---------|
16
+ | Key-value lookup | O(1) avg | O(log n) |
17
+ | Insert / delete | O(1) avg | O(log n) |
18
+ | Sorted iteration | ❌ | ✅ |
19
+ | Floor (largest key ≤ x) | ❌ | O(log n) |
20
+ | Ceiling (smallest key ≥ x) | ❌ | O(log n) |
21
+ | Range query | ❌ | O(log n + k) |
22
+ | getRank / getByRank | ❌ | O(log n) |
23
+ | First / last key | ❌ | O(log n) |
24
+ | Memory | Lower | Higher |
25
+
26
+ ## When Map Is the Right Choice
27
+
28
+ ```typescript
29
+ // User lookup by ID — order doesn't matter
30
+ const users = new Map<string, User>();
31
+ users.set('abc123', { name: 'Alice' });
32
+ users.get('abc123'); // O(1)
33
+ ```
34
+
35
+ Use `Map` when:
36
+ - You only need get/set/delete by exact key
37
+ - Order doesn't matter
38
+ - Performance on individual lookups is critical (O(1) vs O(log n))
39
+
40
+ ## When TreeMap Is the Right Choice
41
+
42
+ ### Sorted iteration
43
+ ```typescript
44
+ import { TreeMap } from 'data-structure-typed';
45
+
46
+ const config = new TreeMap<string, string>();
47
+ config.set('database.host', 'localhost');
48
+ config.set('app.name', 'MyApp');
49
+ config.set('database.port', '5432');
50
+
51
+ for (const [key, value] of config) {
52
+ console.log(key, value);
53
+ }
54
+ // app.name MyApp
55
+ // database.host localhost
56
+ // database.port 5432
57
+ ```
58
+
59
+ ### Finding nearest keys
60
+ ```typescript
61
+ const prices = new TreeMap<number, string>();
62
+ prices.set(10, 'cheap');
63
+ prices.set(50, 'medium');
64
+ prices.set(100, 'expensive');
65
+
66
+ // "What's the price tier for $35?"
67
+ prices.floor(35); // [10, 'cheap'] — largest key ≤ 35
68
+ prices.ceiling(35); // [50, 'medium'] — smallest key ≥ 35
69
+ ```
70
+
71
+ ### Range queries
72
+ ```typescript
73
+ const events = new TreeMap<number, string>();
74
+ events.set(1000, 'login');
75
+ events.set(2000, 'click');
76
+ events.set(3000, 'purchase');
77
+ events.set(4000, 'logout');
78
+
79
+ // Events between t=1500 and t=3500
80
+ events.rangeSearch([1500, 3500]); // [[2000, 'click'], [3000, 'purchase']]
81
+ ```
82
+
83
+ ### Rank queries
84
+ ```typescript
85
+ const leaderboard = new TreeMap<number, string>(
86
+ [[100, 'Alice'], [250, 'Bob'], [180, 'Charlie']],
87
+ { enableOrderStatistic: true }
88
+ );
89
+
90
+ leaderboard.getRank(180); // 1 — Charlie is at position 1
91
+ leaderboard.getByRank(0); // [100, 'Alice'] — first in tree order
92
+ ```
93
+
94
+ ## Performance: When Does TreeMap Win?
95
+
96
+ For pure get/set, Map is faster (O(1) vs O(log n)). TreeMap wins when you need **ordered operations**:
97
+
98
+ | 10,000 entries | Map | TreeMap |
99
+ |----------------|-----|---------|
100
+ | set() | ~0.5μs | ~2μs |
101
+ | get() | ~0.3μs | ~1.5μs |
102
+ | floor() | N/A (manual O(n)) | ~1.5μs |
103
+ | rangeSearch() | N/A (manual O(n log n)) | ~5μs + O(k) |
104
+ | Sorted iteration | O(n log n) sort first | O(n) |
105
+
106
+ If you're calling `.floor()` or `.rangeSearch()` frequently, TreeMap is orders of magnitude faster than manually sorting Map keys every time.
107
+
108
+ ## Set vs TreeSet — Same Story
109
+
110
+ | Feature | Set | TreeSet |
111
+ |---------|-----|---------|
112
+ | Membership check | O(1) avg | O(log n) |
113
+ | Sorted iteration | ❌ | ✅ |
114
+ | Floor / ceiling | ❌ | O(log n) |
115
+ | Range queries | ❌ | O(log n + k) |
116
+ | First / last | ❌ | O(log n) |
117
+
118
+ ```typescript
119
+ import { TreeSet } from 'data-structure-typed';
120
+
121
+ const timestamps = new TreeSet<number>([1000, 3000, 2000, 5000]);
122
+ [...timestamps]; // [1000, 2000, 3000, 5000]
123
+ timestamps.floor(2500); // 2000
124
+ timestamps.ceiling(2500); // 3000
125
+ ```
126
+
127
+ ## Migration Guide: Map → TreeMap
128
+
129
+ TreeMap implements the same interface patterns as Map:
130
+
131
+ ```typescript
132
+ // Map
133
+ const map = new Map<string, number>();
134
+ map.set('a', 1);
135
+ map.get('a');
136
+ map.has('a');
137
+ map.delete('a');
138
+ map.size;
139
+ for (const [k, v] of map) { ... }
140
+
141
+ // TreeMap — same API, plus ordered operations
142
+ const tree = new TreeMap<string, number>();
143
+ tree.set('a', 1);
144
+ tree.get('a');
145
+ tree.has('a');
146
+ tree.delete('a');
147
+ tree.size;
148
+ for (const [k, v] of tree) { ... } // sorted!
149
+ tree.floor('b'); // bonus
150
+ tree.rangeSearch(['a', 'z']); // bonus
151
+ ```
@@ -0,0 +1,113 @@
1
+ ---
2
+ title: Priority Queue in TypeScript — Complete Guide
3
+ description: How to implement a priority queue in TypeScript using Heap, MinHeap, and MaxHeap. Covers task scheduling, top-k problems, and Dijkstra's algorithm.
4
+ keywords: [priority queue typescript, heap typescript, min heap javascript, max heap javascript, task scheduler, top-k]
5
+ sidebar_label: Priority Queue
6
+ ---
7
+
8
+ # Priority Queue in TypeScript
9
+
10
+ A **priority queue** processes elements by priority, not insertion order. In TypeScript, there is no built-in priority queue — but you can use a **Heap** to get O(log n) insert and O(1) access to the highest-priority element.
11
+
12
+ ## The Problem
13
+
14
+ You have tasks with different priorities. Using a sorted array:
15
+
16
+ ```typescript
17
+ // ❌ Array approach — O(n) insert to maintain sorted order
18
+ const tasks: [number, string][] = [];
19
+
20
+ function addTask(priority: number, name: string) {
21
+ tasks.push([priority, name]);
22
+ tasks.sort((a, b) => a[0] - b[0]); // O(n log n) every time!
23
+ }
24
+ ```
25
+
26
+ With 10,000 tasks, this gets slow fast.
27
+
28
+ ## The Solution
29
+
30
+ ```typescript
31
+ import { MinPriorityQueue } from 'data-structure-typed';
32
+
33
+ // O(log n) insert, O(1) peek, O(log n) poll
34
+ const tasks = new MinPriorityQueue<[number, string]>({
35
+ comparator: (a, b) => a[0] - b[0]
36
+ });
37
+
38
+ tasks.add([3, 'Send email']);
39
+ tasks.add([1, 'Fix critical bug']);
40
+ tasks.add([2, 'Review PR']);
41
+
42
+ tasks.poll(); // [1, 'Fix critical bug'] — highest priority first
43
+ tasks.poll(); // [2, 'Review PR']
44
+ tasks.poll(); // [3, 'Send email']
45
+ ```
46
+
47
+ ## When to Use a Priority Queue
48
+
49
+ | Scenario | Why Heap? |
50
+ |----------|-----------|
51
+ | Task scheduling | Process highest-priority task first |
52
+ | Top-k elements | Find k largest/smallest in O(n log k) |
53
+ | Dijkstra's algorithm | Always expand the nearest unvisited node |
54
+ | Event simulation | Process next event by timestamp |
55
+ | Median finding | Two heaps (min + max) for O(log n) median |
56
+
57
+ ## MinHeap vs MaxHeap vs Custom
58
+
59
+ ```typescript
60
+ import { MinHeap, MaxHeap, Heap } from 'data-structure-typed';
61
+
62
+ // Numbers — built-in comparison
63
+ const minHeap = new MinHeap<number>([5, 3, 8, 1]);
64
+ minHeap.peek(); // 1
65
+
66
+ const maxHeap = new MaxHeap<number>([5, 3, 8, 1]);
67
+ maxHeap.peek(); // 8
68
+
69
+ // Objects — custom comparator
70
+ const taskHeap = new Heap<{ priority: number; name: string }>({
71
+ comparator: (a, b) => a.priority - b.priority
72
+ });
73
+ taskHeap.add({ priority: 2, name: 'Review PR' });
74
+ taskHeap.add({ priority: 1, name: 'Fix bug' });
75
+ taskHeap.peek(); // { priority: 1, name: 'Fix bug' }
76
+ ```
77
+
78
+ ## Top-K Problem
79
+
80
+ Find the 3 highest scores from a stream:
81
+
82
+ ```typescript
83
+ import { MinHeap } from 'data-structure-typed';
84
+
85
+ function topK(stream: number[], k: number): number[] {
86
+ const heap = new MinHeap<number>();
87
+ for (const val of stream) {
88
+ heap.add(val);
89
+ if (heap.size > k) heap.poll(); // remove smallest
90
+ }
91
+ return heap.toArray().sort((a, b) => b - a);
92
+ }
93
+
94
+ topK([3, 1, 4, 1, 5, 9, 2, 6, 5], 3); // [9, 6, 5]
95
+ ```
96
+
97
+ Time: O(n log k) — much better than sorting the entire array.
98
+
99
+ ## Complexity
100
+
101
+ | Operation | Array (sorted) | Heap |
102
+ |-----------|---------------|------|
103
+ | Insert | O(n) | O(log n) |
104
+ | Get min/max | O(1) | O(1) |
105
+ | Remove min/max | O(1) | O(log n) |
106
+ | Search | O(log n) | O(n) |
107
+
108
+ ## When NOT to Use a Heap
109
+
110
+ - You need to search for arbitrary elements → use a Tree or HashMap
111
+ - You need sorted iteration of all elements → use TreeMap/TreeSet
112
+ - Your data is small (< 100 elements) → array sort is fine
113
+ - You need both min and max → use two heaps or a TreeMap
@@ -0,0 +1,151 @@
1
+ ---
2
+ title: TreeMap and TreeSet in JavaScript — The Missing Collections
3
+ description: JavaScript doesn't have TreeMap or TreeSet. Here's how to get sorted maps, ordered sets, floor/ceiling lookups, and range queries in TypeScript/JavaScript.
4
+ keywords: [treemap javascript, treeset javascript, sorted map typescript, ordered set javascript, java treemap equivalent, sorted collection]
5
+ sidebar_label: TreeMap / TreeSet
6
+ ---
7
+
8
+ # TreeMap and TreeSet in JavaScript
9
+
10
+ Java has `TreeMap` and `TreeSet`. C++ has `std::map` and `std::set`. Python has `SortedDict` and `SortedSet`. JavaScript has... nothing built-in for sorted collections.
11
+
12
+ `Map` and `Set` in JavaScript are **hash-based** — they don't maintain sorted order and don't support range queries, floor/ceiling, or ordered iteration by key.
13
+
14
+ ## The Problem
15
+
16
+ ```typescript
17
+ // ❌ Native Map — no sorted iteration, no range queries
18
+ const map = new Map<number, string>();
19
+ map.set(3, 'c');
20
+ map.set(1, 'a');
21
+ map.set(2, 'b');
22
+ [...map.keys()]; // [3, 1, 2] — insertion order, NOT sorted
23
+
24
+ // ❌ To find "largest key ≤ 2.5" you'd need to sort all keys first
25
+ const keys = [...map.keys()].sort((a, b) => a - b);
26
+ // Then binary search... every time. O(n log n).
27
+ ```
28
+
29
+ ## The Solution
30
+
31
+ ```typescript
32
+ import { TreeMap } from 'data-structure-typed';
33
+
34
+ const map = new TreeMap<number, string>();
35
+ map.set(3, 'c');
36
+ map.set(1, 'a');
37
+ map.set(2, 'b');
38
+
39
+ // ✅ Sorted iteration
40
+ [...map.keys()]; // [1, 2, 3]
41
+
42
+ // ✅ NavigableMap operations — O(log n)
43
+ map.floor(2.5); // [2, 'b'] — largest key ≤ 2.5
44
+ map.ceiling(1.5); // [2, 'b'] — smallest key ≥ 1.5
45
+ map.higher(2); // [3, 'c'] — smallest key > 2
46
+ map.lower(2); // [1, 'a'] — largest key < 2
47
+
48
+ // ✅ Range queries
49
+ map.rangeSearch([1, 2]); // [[1, 'a'], [2, 'b']]
50
+ ```
51
+
52
+ ## TreeSet — Sorted Set
53
+
54
+ ```typescript
55
+ import { TreeSet } from 'data-structure-typed';
56
+
57
+ const set = new TreeSet<number>([5, 3, 8, 1, 4]);
58
+
59
+ [...set]; // [1, 3, 4, 5, 8] — always sorted
60
+
61
+ set.floor(4.5); // 4
62
+ set.ceiling(3.5); // 4
63
+ set.higher(5); // 8
64
+ set.lower(3); // 1
65
+
66
+ // First and last
67
+ set.first(); // 1
68
+ set.last(); // 8
69
+ ```
70
+
71
+ ## Order-Statistic Operations
72
+
73
+ Need to know "what's the 3rd element?" or "what rank is this key?"
74
+
75
+ ```typescript
76
+ import { TreeMap } from 'data-structure-typed';
77
+
78
+ const scores = new TreeMap<number, string>(
79
+ [[100, 'Alice'], [250, 'Bob'], [180, 'Charlie']],
80
+ { enableOrderStatistic: true }
81
+ );
82
+
83
+ scores.getByRank(0); // [100, 'Alice'] — first in tree order
84
+ scores.getByRank(2); // [250, 'Bob'] — third in tree order
85
+ scores.getRank(180); // 1 — Charlie is at position 1
86
+ scores.rangeByRank(0, 1); // [[100, 'Alice'], [180, 'Charlie']]
87
+ ```
88
+
89
+ ## Map vs TreeMap — When to Use Which
90
+
91
+ | Feature | Map | TreeMap |
92
+ |---------|-----|---------|
93
+ | Sorted iteration | ❌ | ✅ |
94
+ | floor / ceiling | ❌ | ✅ |
95
+ | Range queries | ❌ | ✅ |
96
+ | getRank / getByRank | ❌ | ✅ |
97
+ | Insert / lookup | O(1) avg | O(log n) |
98
+ | Memory | Lower | Higher |
99
+
100
+ **Use Map** when you only need key-value lookup and don't care about order.
101
+
102
+ **Use TreeMap** when you need sorted keys, range queries, floor/ceiling, or rank operations.
103
+
104
+ ## Real-World Use Cases
105
+
106
+ ### Price book (financial trading)
107
+ ```typescript
108
+ const orderBook = new TreeMap<number, number>(); // price → quantity
109
+ orderBook.set(100.5, 200);
110
+ orderBook.set(101.0, 150);
111
+ orderBook.set(99.5, 300);
112
+
113
+ // Best bid (highest price)
114
+ orderBook.last(); // [101.0, 150]
115
+ // All orders between $100 and $101
116
+ orderBook.rangeSearch([100, 101]); // [[100.5, 200], [101.0, 150]]
117
+ ```
118
+
119
+ ### Time-series data
120
+ ```typescript
121
+ const events = new TreeMap<number, string>(); // timestamp → event
122
+ events.set(1000, 'start');
123
+ events.set(2000, 'checkpoint');
124
+ events.set(3000, 'end');
125
+
126
+ // What happened at or before t=2500?
127
+ events.floor(2500); // [2000, 'checkpoint']
128
+ ```
129
+
130
+ ### Leaderboard
131
+ ```typescript
132
+ const leaderboard = new TreeMap<number, string>(
133
+ [[100, 'Alice'], [250, 'Bob'], [180, 'Charlie']],
134
+ { comparator: (a, b) => b - a, enableOrderStatistic: true }
135
+ );
136
+
137
+ // Top 3
138
+ leaderboard.rangeByRank(0, 2);
139
+ // [[250, 'Bob'], [180, 'Charlie'], [100, 'Alice']]
140
+ ```
141
+
142
+ ## Complexity
143
+
144
+ | Operation | TreeMap | Sorted Array | Native Map |
145
+ |-----------|---------|-------------|------------|
146
+ | Insert | O(log n) | O(n) | O(1) avg |
147
+ | Delete | O(log n) | O(n) | O(1) avg |
148
+ | Lookup | O(log n) | O(log n) | O(1) avg |
149
+ | Floor/Ceiling | O(log n) | O(log n) | ❌ |
150
+ | Sorted iteration | O(n) | O(n) | ❌ |
151
+ | Range query | O(log n + k) | O(log n + k) | ❌ |
@@ -53,7 +53,7 @@ const config: Config = {
53
53
  '@context': 'https://schema.org',
54
54
  '@type': 'SoftwareSourceCode',
55
55
  name: 'data-structure-typed',
56
- description: 'A comprehensive TypeScript and JavaScript data structures library featuring production-ready implementations, zero dependencies, and an intuitive Array-like API.',
56
+ description: 'Production-ready TypeScript data structures library Heap, Priority Queue, TreeMap, TreeSet, Red-Black Tree, Trie, Graph, Deque, SkipList. Zero dependencies, type-safe, with getRank/getByRank/rangeByRank support.',
57
57
  url: 'https://data-structure-typed-docs.vercel.app',
58
58
  codeRepository: 'https://github.com/zrwusa/data-structure-typed',
59
59
  programmingLanguage: ['TypeScript', 'JavaScript'],