Open History to see the last commit
1import { compareKeys } from '@tanstack/db-ivm'
2
3/**
4 * A Map implementation that keeps its entries sorted based on a comparator function
5 * @template TKey - The type of keys in the map (must be string | number)
6 * @template TValue - The type of values in the map
7 */
8export class SortedMap<TKey extends string | number, TValue> {
9 private map: Map<TKey, TValue>
10 private sortedKeys: Array<TKey>
11 private comparator: ((a: TValue, b: TValue) => number) | undefined
12
13 /**
14 * Creates a new SortedMap instance
15 *
16 * @param comparator - Optional function to compare values for sorting.
17 * If not provided, entries are sorted by key only.
18 */
19 constructor(comparator?: (a: TValue, b: TValue) => number) {
20 this.map = new Map<TKey, TValue>()
21 this.sortedKeys = []
22 this.comparator = comparator
23 }
24
25 /**
26 * Finds the index where a key-value pair should be inserted to maintain sort order.
27 * Uses binary search to find the correct position based on the value (if comparator provided),
28 * with key-based tie-breaking for deterministic ordering when values compare as equal.
29 * If no comparator is provided, sorts by key only.
30 * Runs in O(log n) time.
31 *
32 * @param key - The key to find position for (used as tie-breaker or primary sort when no comparator)
33 * @param value - The value to compare against (only used if comparator is provided)
34 * @returns The index where the key should be inserted
35 */
36 private indexOf(key: TKey, value: TValue): number {
37 let left = 0
38 let right = this.sortedKeys.length
39
40 // Fast path: no comparator means sort by key only
41 if (!this.comparator) {
42 while (left < right) {
43 const mid = Math.floor((left + right) / 2)
44 const midKey = this.sortedKeys[mid]!
45 const keyComparison = compareKeys(key, midKey)
46 if (keyComparison < 0) {
47 right = mid
48 } else if (keyComparison > 0) {
49 left = mid + 1
50 } else {
51 return mid
52 }
53 }
54 return left
55 }
56
57 // With comparator: sort by value first, then key as tie-breaker
58 while (left < right) {
59 const mid = Math.floor((left + right) / 2)
60 const midKey = this.sortedKeys[mid]!
61 const midValue = this.map.get(midKey)!
62 const valueComparison = this.comparator(value, midValue)
63
64 if (valueComparison < 0) {
65 right = mid
66 } else if (valueComparison > 0) {
67 left = mid + 1
68 } else {
69 // Values are equal, use key as tie-breaker for deterministic ordering
70 const keyComparison = compareKeys(key, midKey)
71 if (keyComparison < 0) {
72 right = mid
73 } else if (keyComparison > 0) {
74 left = mid + 1
75 } else {
76 // Same key (shouldn't happen during insert, but handle for lookups)
77 return mid
78 }
79 }
80 }
81
82 return left
83 }
84
85 /**
86 * Sets a key-value pair in the map and maintains sort order
87 *
88 * @param key - The key to set
89 * @param value - The value to associate with the key
90 * @returns This SortedMap instance for chaining
91 */
92 set(key: TKey, value: TValue): this {
93 if (this.map.has(key)) {
94 // Need to remove the old key from the sorted keys array
95 const oldValue = this.map.get(key)!
96 const oldIndex = this.indexOf(key, oldValue)
97 this.sortedKeys.splice(oldIndex, 1)
98 }
99
100 // Insert the new key at the correct position
101 const index = this.indexOf(key, value)
102 this.sortedKeys.splice(index, 0, key)
103
104 this.map.set(key, value)
105
106 return this
107 }
108
109 /**
110 * Gets a value by its key
111 *
112 * @param key - The key to look up
113 * @returns The value associated with the key, or undefined if not found
114 */
115 get(key: TKey): TValue | undefined {
116 return this.map.get(key)
117 }
118
119 /**
120 * Removes a key-value pair from the map
121 *
122 * @param key - The key to remove
123 * @returns True if the key was found and removed, false otherwise
124 */
125 delete(key: TKey): boolean {
126 if (this.map.has(key)) {
127 const oldValue = this.map.get(key)
128 const index = this.indexOf(key, oldValue!)
129 this.sortedKeys.splice(index, 1)
130 return this.map.delete(key)
131 }
132
133 return false
134 }
135
136 /**
137 * Checks if a key exists in the map
138 *
139 * @param key - The key to check
140 * @returns True if the key exists, false otherwise
141 */
142 has(key: TKey): boolean {
143 return this.map.has(key)
144 }
145
146 /**
147 * Removes all key-value pairs from the map
148 */
149 clear(): void {
150 this.map.clear()
151 this.sortedKeys = []
152 }
153
154 /**
155 * Gets the number of key-value pairs in the map
156 */
157 get size(): number {
158 return this.map.size
159 }
160
161 /**
162 * Default iterator that returns entries in sorted order
163 *
164 * @returns An iterator for the map's entries
165 */
166 *[Symbol.iterator](): IterableIterator<[TKey, TValue]> {
167 for (const key of this.sortedKeys) {
168 yield [key, this.map.get(key)!] as [TKey, TValue]
169 }
170 }
171
172 /**
173 * Returns an iterator for the map's entries in sorted order
174 *
175 * @returns An iterator for the map's entries
176 */
177 entries(): IterableIterator<[TKey, TValue]> {
178 return this[Symbol.iterator]()
179 }
180
181 /**
182 * Returns an iterator for the map's keys in sorted order
183 *
184 * @returns An iterator for the map's keys
185 */
186 keys(): IterableIterator<TKey> {
187 return this.sortedKeys[Symbol.iterator]()
188 }
189
190 /**
191 * Returns an iterator for the map's values in sorted order
192 *
193 * @returns An iterator for the map's values
194 */
195 values(): IterableIterator<TValue> {
196 return function* (this: SortedMap<TKey, TValue>) {
197 for (const key of this.sortedKeys) {
198 yield this.map.get(key)!
199 }
200 }.call(this)
201 }
202
203 /**
204 * Executes a callback function for each key-value pair in the map in sorted order
205 *
206 * @param callbackfn - Function to execute for each entry
207 */
208 forEach(
209 callbackfn: (value: TValue, key: TKey, map: Map<TKey, TValue>) => void,
210 ): void {
211 for (const key of this.sortedKeys) {
212 callbackfn(this.map.get(key)!, key, this.map)
213 }
214 }
215}