Open History to see the last commit
1import { generateKeyBetween } from 'fractional-indexing'
2import { binarySearch, compareKeys, diffHalfOpen } from '../utils.js'
3import type { HRange } from '../utils.js'
4
5// Abstraction for fractionally indexed values
6export type FractionalIndex = string
7export type IndexedValue<V> = [V, FractionalIndex]
8
9export function indexedValue<V>(
10 value: V,
11 index: FractionalIndex,
12): IndexedValue<V> {
13 return [value, index]
14}
15
16export function getValue<V>(indexedVal: IndexedValue<V>): V {
17 return indexedVal[0]
18}
19
20export function getIndex<V>(indexedVal: IndexedValue<V>): FractionalIndex {
21 return indexedVal[1]
22}
23
24/**
25 * Creates a comparator for [key, value] tuples that first compares values,
26 * then uses the row key as a stable tie-breaker.
27 */
28export function createKeyedComparator<K extends string | number, T>(
29 comparator: (a: T, b: T) => number,
30): (a: [K, T], b: [K, T]) => number {
31 return ([aKey, aVal], [bKey, bVal]) => {
32 // First compare on the value
33 const valueComparison = comparator(aVal, bVal)
34 if (valueComparison !== 0) {
35 return valueComparison
36 }
37 // If the values are equal, use the row key as tie-breaker
38 // This provides stable, deterministic ordering since keys are string | number
39 return compareKeys(aKey, bKey)
40 }
41}
42
43export type TopKChanges<V> = {
44 /** Indicates which element moves into the topK (if any) */
45 moveIn: IndexedValue<V> | null
46 /** Indicates which element moves out of the topK (if any) */
47 moveOut: IndexedValue<V> | null
48}
49
50export type TopKMoveChanges<V> = {
51 /** Flag that marks whether there were any changes to the topK */
52 changes: boolean
53 /** Indicates which elements move into the topK (if any) */
54 moveIns: Array<IndexedValue<V>>
55 /** Indicates which elements move out of the topK (if any) */
56 moveOuts: Array<IndexedValue<V>>
57}
58
59/**
60 * A topK data structure that supports insertions and deletions
61 * and returns changes to the topK.
62 */
63export interface TopK<V> {
64 size: number
65 /**
66 * The number of leading window values that satisfy a predicate that holds
67 * for a prefix of the window order. Optional; a caller falls back to size.
68 */
69 countLeadingInWindow?: (predicate: (value: V) => boolean) => number
70 insert: (value: V) => TopKChanges<V>
71 delete: (value: V) => TopKChanges<V>
72}
73
74/**
75 * Implementation of a topK data structure.
76 * Uses a sorted array internally to store the values and keeps a topK window over that array.
77 * Inserts and deletes are O(n) operations because worst case an element is inserted/deleted
78 * at the start of the array which causes all the elements to shift to the right/left.
79 */
80export class TopKArray<V> implements TopK<V> {
81 #sortedValues: Array<IndexedValue<V>> = []
82 #comparator: (a: V, b: V) => number
83 #topKStart: number
84 #topKEnd: number
85
86 constructor(
87 offset: number,
88 limit: number,
89 comparator: (a: V, b: V) => number,
90 ) {
91 this.#topKStart = offset
92 this.#topKEnd = offset + limit
93 this.#comparator = comparator
94 }
95
96 get size(): number {
97 const offset = this.#topKStart
98 const limit = this.#topKEnd - this.#topKStart
99 const available = this.#sortedValues.length - offset
100 return Math.max(0, Math.min(limit, available))
101 }
102
103 countLeadingInWindow(predicate: (value: V) => boolean): number {
104 let count = 0
105 const end = this.#topKStart + this.size
106 for (let index = this.#topKStart; index < end; index++) {
107 if (!predicate(getValue(this.#sortedValues[index]!))) break
108 count++
109 }
110 return count
111 }
112
113 /**
114 * Moves the topK window
115 */
116 move({
117 offset,
118 limit,
119 }: {
120 offset?: number
121 limit?: number
122 }): TopKMoveChanges<V> {
123 const oldOffset = this.#topKStart
124 const oldLimit = this.#topKEnd - this.#topKStart
125
126 // `this.#topKEnd` can be `Infinity` if it has no limit
127 // but `diffHalfOpen` expects a finite range
128 // so we restrict it to the size of the topK if topKEnd is infinite
129 const oldRange: HRange = [
130 this.#topKStart,
131 this.#topKEnd === Infinity ? this.#topKStart + this.size : this.#topKEnd,
132 ]
133
134 this.#topKStart = offset ?? oldOffset
135 this.#topKEnd = this.#topKStart + (limit ?? oldLimit) // can be `Infinity` if limit is `Infinity`
136
137 // Also handle `Infinity` in the newRange
138 const newRange: HRange = [
139 this.#topKStart,
140 this.#topKEnd === Infinity
141 ? Math.max(this.#topKStart + this.size, oldRange[1]) // since the new limit is Infinity we need to take everything (so we need to take the biggest (finite) topKEnd)
142 : this.#topKEnd,
143 ]
144 const { onlyInA, onlyInB } = diffHalfOpen(oldRange, newRange)
145
146 const moveIns: Array<IndexedValue<V>> = []
147 onlyInB.forEach((index) => {
148 const value = this.#sortedValues[index]
149 if (value) {
150 moveIns.push(value)
151 }
152 })
153
154 const moveOuts: Array<IndexedValue<V>> = []
155 onlyInA.forEach((index) => {
156 const value = this.#sortedValues[index]
157 if (value) {
158 moveOuts.push(value)
159 }
160 })
161
162 // It could be that there are changes (i.e. moveIns or moveOuts)
163 // but that the collection is lazy so we don't have the data yet that needs to move in/out
164 // so `moveIns` and `moveOuts` will be empty but `changes` will be true
165 // this will tell the caller that it needs to run the graph to load more data
166 return { moveIns, moveOuts, changes: onlyInA.length + onlyInB.length > 0 }
167 }
168
169 insert(value: V): TopKChanges<V> {
170 const result: TopKChanges<V> = { moveIn: null, moveOut: null }
171
172 // Lookup insert position
173 const index = this.#findIndex(value)
174 // Generate fractional index based on the fractional indices of the elements before and after it
175 const indexBefore =
176 index === 0 ? null : getIndex(this.#sortedValues[index - 1]!)
177 const indexAfter =
178 index === this.#sortedValues.length
179 ? null
180 : getIndex(this.#sortedValues[index]!)
181 const fractionalIndex = generateKeyBetween(indexBefore, indexAfter)
182
183 // Insert the value at the correct position
184 const val = indexedValue(value, fractionalIndex)
185 // Splice is O(n) where n = all elements in the collection (i.e. n >= k) !
186 this.#sortedValues.splice(index, 0, val)
187
188 if (this.#topKStart === this.#topKEnd) return result
189
190 // Check if the topK changed
191 if (index < this.#topKEnd) {
192 // The inserted element is either before the top K or within the top K
193 // If it is before the top K then it moves the element that was right before the topK into the topK
194 // If it is within the top K then the inserted element moves into the top K
195 // In both cases the last element of the old top K now moves out of the top K
196 const moveInIndex = Math.max(index, this.#topKStart)
197 if (moveInIndex < this.#sortedValues.length) {
198 // We actually have a topK
199 // because in some cases there may not be enough elements in the array to reach the start of the topK
200 // e.g. [1, 2, 3] with K = 2 and offset = 3 does not have a topK
201 result.moveIn = this.#sortedValues[moveInIndex]!
202
203 // We need to remove the element that falls out of the top K
204 // The element that falls out of the top K has shifted one to the right
205 // because of the element we inserted, so we find it at index topKEnd
206 if (this.#topKEnd < this.#sortedValues.length) {
207 result.moveOut = this.#sortedValues[this.#topKEnd]!
208 }
209 }
210 }
211
212 return result
213 }
214
215 /**
216 * Deletes a value that may or may not be in the topK.
217 * IMPORTANT: this assumes that the value is present in the collection
218 * if it's not the case it will remove the element
219 * that is on the position where the provided `value` would be.
220 */
221 delete(value: V): TopKChanges<V> {
222 const result: TopKChanges<V> = { moveIn: null, moveOut: null }
223
224 // Lookup delete position
225 const index = this.#findIndex(value)
226 // Remove the value at that position
227 const [removedElem] = this.#sortedValues.splice(index, 1)
228
229 if (this.#topKStart === this.#topKEnd) return result
230
231 // Check if the topK changed
232 if (index < this.#topKEnd) {
233 // The removed element is either before the top K or within the top K
234 // If it is before the top K then the first element of the topK moves out of the topK
235 // If it is within the top K then the removed element moves out of the topK
236 result.moveOut = removedElem!
237 if (index < this.#topKStart) {
238 // The removed element is before the topK
239 // so actually, the first element of the topK moves out of the topK
240 // and not the element that we removed
241 // The first element of the topK is now at index topKStart - 1
242 // since we removed an element before the topK
243 const moveOutIndex = this.#topKStart - 1
244 if (moveOutIndex < this.#sortedValues.length) {
245 result.moveOut = this.#sortedValues[moveOutIndex]!
246 } else {
247 // No value is moving out of the topK
248 // because there are no elements in the topK
249 result.moveOut = null
250 }
251 }
252
253 // Since we removed an element that was before or in the topK
254 // the first element after the topK moved one position to the left
255 // and thus falls into the topK now
256 const moveInIndex = this.#topKEnd - 1
257 if (moveInIndex < this.#sortedValues.length) {
258 result.moveIn = this.#sortedValues[moveInIndex]!
259 }
260 }
261
262 return result
263 }
264
265 // TODO: see if there is a way to refactor the code for insert and delete in the topK above
266 // because they are very similar, one is shifting the topK window to the left and the other is shifting it to the right
267 // so i have the feeling there is a common pattern here and we can implement both cases using that pattern
268
269 #findIndex(value: V): number {
270 return binarySearch(this.#sortedValues, indexedValue(value, ``), (a, b) =>
271 this.#comparator(getValue(a), getValue(b)),
272 )
273 }
274}