Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

SortedMap.ts

255 lines7.8 KB

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 // Keys set or deleted with deferOrder since the last restoreOrder. A dirty
13 // key can still hold a slot in sortedKeys that its old value ordered.
14 private dirtyKeys = new Set<TKey>()
15​
16 /**
17 * Creates a new SortedMap instance
18 *
19 * @param comparator - Optional function to compare values for sorting.
20 * If not provided, entries are sorted by key only.
21 */
22 constructor(comparator?: (a: TValue, b: TValue) => number) {
23 this.map = new Map<TKey, TValue>()
24 this.sortedKeys = []
25 this.comparator = comparator
26 }
27​
28 /**
29 * Finds the index where a key-value pair should be inserted to maintain sort order.
30 * Uses binary search to find the correct position based on the value (if comparator provided),
31 * with key-based tie-breaking for deterministic ordering when values compare as equal.
32 * If no comparator is provided, sorts by key only.
33 * Runs in O(log n) time.
34 *
35 * @param key - The key to find position for (used as tie-breaker or primary sort when no comparator)
36 * @param value - The value to compare against (only used if comparator is provided)
37 * @param keys - The ordered keys to search
38 * @returns The index where the key should be inserted
39 */
40 private indexOf(
41 key: TKey,
42 value: TValue,
43 keys: Array<TKey> = this.sortedKeys,
44 ): number {
45 let left = 0
46 let right = keys.length
47​
48 // Fast path: no comparator means sort by key only
49 if (!this.comparator) {
50 while (left < right) {
51 const mid = Math.floor((left + right) / 2)
52 const midKey = keys[mid]!
53 const keyComparison = compareKeys(key, midKey)
54 if (keyComparison < 0) {
55 right = mid
56 } else if (keyComparison > 0) {
57 left = mid + 1
58 } else {
59 return mid
60 }
61 }
62 return left
63 }
64​
65 // With comparator: sort by value first, then key as tie-breaker
66 while (left < right) {
67 const mid = Math.floor((left + right) / 2)
68 const midKey = keys[mid]!
69 const midValue = this.map.get(midKey)!
70 const valueComparison = this.comparator(value, midValue)
71​
72 if (valueComparison < 0) {
73 right = mid
74 } else if (valueComparison > 0) {
75 left = mid + 1
76 } else {
77 // Values are equal, use key as tie-breaker for deterministic ordering
78 const keyComparison = compareKeys(key, midKey)
79 if (keyComparison < 0) {
80 right = mid
81 } else if (keyComparison > 0) {
82 left = mid + 1
83 } else {
84 // Same key (shouldn't happen during insert, but handle for lookups)
85 return mid
86 }
87 }
88 }
89​
90 return left
91 }
92​
93 /**
94 * Restore the ordered view after a synchronous batch of deferred writes.
95 * Dirty keys leave their old slots by Set membership, so a deleted value or
96 * one a sync source mutated in place cannot strand a slot. The dirty keys
97 * still present are sorted and merged into the rest in one pass:
98 * O(n + k log n) for k dirty keys. The merge rewrites sortedKeys in place,
99 * so an open key iterator reads the restored order.
100 */
101 restoreOrder(): void {
102 if (this.dirtyKeys.size === 0) return
103 const keys = this.sortedKeys
104 const kept = keys.filter((key) => !this.dirtyKeys.has(key))
105 const placed = [...this.dirtyKeys]
106 .filter((key) => this.map.has(key))
107 .sort(
108 (left, right) =>
109 (this.comparator?.(this.map.get(left)!, this.map.get(right)!) ?? 0) ||
110 compareKeys(left, right),
111 )
112 keys.length = 0
113 let next = 0
114 for (const key of placed) {
115 const index = this.indexOf(key, this.map.get(key)!, kept)
116 while (next < index) keys.push(kept[next++]!)
117 keys.push(key)
118 }
119 while (next < kept.length) keys.push(kept[next++]!)
120 this.dirtyKeys.clear()
121 }
122​
123 /** Removes a key's slot while its placed value is still mapped. */
124 private unplace(key: TKey): void {
125 // Binary search misses a value that a sync source mutated in place after
126 // it was placed, so fall back to a scan. Slots compare as Map keys do, so
127 // a NaN key matches its own slot.
128 const sameKey = (candidate: TKey) =>
129 candidate === key || (candidate !== candidate && key !== key)
130 let index = this.indexOf(key, this.map.get(key)!)
131 if (!sameKey(this.sortedKeys[index]!)) {
132 index = this.sortedKeys.findIndex(sameKey)
133 }
134 this.sortedKeys.splice(index, 1)
135 }
136​
137 /**
138 * Sets a key-value pair in the map and maintains sort order
139 *
140 * @param key - The key to set
141 * @param value - The value to associate with the key
142 * @param deferOrder - Defer ordering until restoreOrder or the next ordered read
143 * @returns This SortedMap instance for chaining
144 */
145 set(key: TKey, value: TValue, deferOrder = false): this {
146 // Key order cannot change when an existing key gets a new value.
147 if (!this.comparator && this.map.has(key)) {
148 this.map.set(key, value)
149 return this
150 }
151 if (deferOrder) {
152 this.map.set(key, value)
153 this.dirtyKeys.add(key)
154 return this
155 }
156 this.restoreOrder()
157 // The old slot leaves before the search, since an in-place mutation can
158 // misorder it.
159 if (this.map.has(key)) this.unplace(key)
160 this.sortedKeys.splice(this.indexOf(key, value), 0, key)
161 this.map.set(key, value)
162 return this
163 }
164​
165 /**
166 * Gets a value by its key
167 *
168 * @param key - The key to look up
169 * @returns The value associated with the key, or undefined if not found
170 */
171 get(key: TKey): TValue | undefined {
172 return this.map.get(key)
173 }
174​
175 /**
176 * Removes a key-value pair from the map
177 *
178 * @param key - The key to remove
179 * @param deferOrder - Defer ordering until restoreOrder or the next ordered read
180 * @returns True if the key was found and removed, false otherwise
181 */
182 delete(key: TKey, deferOrder = false): boolean {
183 if (deferOrder) {
184 const deleted = this.map.delete(key)
185 if (deleted) this.dirtyKeys.add(key)
186 return deleted
187 }
188 this.restoreOrder()
189 if (this.map.has(key)) this.unplace(key)
190 return this.map.delete(key)
191 }
192​
193 /**
194 * Checks if a key exists in the map
195 *
196 * @param key - The key to check
197 * @returns True if the key exists, false otherwise
198 */
199 has(key: TKey): boolean {
200 return this.map.has(key)
201 }
202​
203 /**
204 * Removes all key-value pairs from the map
205 */
206 clear(): void {
207 this.map.clear()
208 this.sortedKeys = []
209 this.dirtyKeys.clear()
210 }
211​
212 /**
213 * Gets the number of key-value pairs in the map
214 */
215 get size(): number {
216 return this.map.size
217 }
218​
219 /**
220 * Default iterator that returns entries in sorted order
221 *
222 * @returns An iterator for the map's entries
223 */
224 *[Symbol.iterator](): IterableIterator<[TKey, TValue]> {
225 for (const key of this.keys()) yield [key, this.map.get(key)!]
226 }
227​
228 /**
229 * Returns an iterator for the map's entries in sorted order
230 *
231 * @returns An iterator for the map's entries
232 */
233 entries(): IterableIterator<[TKey, TValue]> {
234 return this[Symbol.iterator]()
235 }
236​
237 /**
238 * Returns an iterator for the map's keys in sorted order
239 *
240 * @returns An iterator for the map's keys
241 */
242 keys(): IterableIterator<TKey> {
243 this.restoreOrder()
244 return this.sortedKeys[Symbol.iterator]()
245 }
246​
247 /**
248 * Returns an iterator for the map's values in sorted order
249 *
250 * @returns An iterator for the map's values
251 */
252 *values(): IterableIterator<TValue> {
253 for (const key of this.keys()) yield this.map.get(key)!
254 }