@tanstack/db-ivm 0.1.14 → 0.1.16

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 (65) hide show
  1. package/dist/cjs/index.cjs +6 -3
  2. package/dist/cjs/index.cjs.map +1 -1
  3. package/dist/cjs/index.d.cts +1 -1
  4. package/dist/cjs/indexes.cjs +1 -1
  5. package/dist/cjs/indexes.cjs.map +1 -1
  6. package/dist/cjs/operators/groupBy.cjs +2 -1
  7. package/dist/cjs/operators/groupBy.cjs.map +1 -1
  8. package/dist/cjs/operators/groupedOrderBy.cjs +33 -0
  9. package/dist/cjs/operators/groupedOrderBy.cjs.map +1 -0
  10. package/dist/cjs/operators/groupedOrderBy.d.cts +31 -0
  11. package/dist/cjs/operators/groupedTopKWithFractionalIndex.cjs +116 -0
  12. package/dist/cjs/operators/groupedTopKWithFractionalIndex.cjs.map +1 -0
  13. package/dist/cjs/operators/groupedTopKWithFractionalIndex.d.cts +50 -0
  14. package/dist/cjs/operators/index.d.cts +2 -0
  15. package/dist/cjs/operators/topKArray.cjs +137 -0
  16. package/dist/cjs/operators/topKArray.cjs.map +1 -0
  17. package/dist/cjs/operators/topKArray.d.cts +59 -0
  18. package/dist/cjs/operators/topKState.cjs +73 -0
  19. package/dist/cjs/operators/topKState.cjs.map +1 -0
  20. package/dist/cjs/operators/topKState.d.cts +35 -0
  21. package/dist/cjs/operators/topKWithFractionalIndex.cjs +14 -190
  22. package/dist/cjs/operators/topKWithFractionalIndex.cjs.map +1 -1
  23. package/dist/cjs/operators/topKWithFractionalIndex.d.cts +1 -32
  24. package/dist/cjs/operators/topKWithFractionalIndexBTree.d.cts +2 -1
  25. package/dist/cjs/utils.cjs +12 -0
  26. package/dist/cjs/utils.cjs.map +1 -1
  27. package/dist/cjs/utils.d.cts +6 -0
  28. package/dist/esm/index.d.ts +1 -1
  29. package/dist/esm/index.js +8 -5
  30. package/dist/esm/index.js.map +1 -1
  31. package/dist/esm/indexes.js +1 -1
  32. package/dist/esm/indexes.js.map +1 -1
  33. package/dist/esm/operators/groupBy.js +2 -1
  34. package/dist/esm/operators/groupBy.js.map +1 -1
  35. package/dist/esm/operators/groupedOrderBy.d.ts +31 -0
  36. package/dist/esm/operators/groupedOrderBy.js +33 -0
  37. package/dist/esm/operators/groupedOrderBy.js.map +1 -0
  38. package/dist/esm/operators/groupedTopKWithFractionalIndex.d.ts +50 -0
  39. package/dist/esm/operators/groupedTopKWithFractionalIndex.js +116 -0
  40. package/dist/esm/operators/groupedTopKWithFractionalIndex.js.map +1 -0
  41. package/dist/esm/operators/index.d.ts +2 -0
  42. package/dist/esm/operators/topKArray.d.ts +59 -0
  43. package/dist/esm/operators/topKArray.js +137 -0
  44. package/dist/esm/operators/topKArray.js.map +1 -0
  45. package/dist/esm/operators/topKState.d.ts +35 -0
  46. package/dist/esm/operators/topKState.js +73 -0
  47. package/dist/esm/operators/topKState.js.map +1 -0
  48. package/dist/esm/operators/topKWithFractionalIndex.d.ts +1 -32
  49. package/dist/esm/operators/topKWithFractionalIndex.js +12 -188
  50. package/dist/esm/operators/topKWithFractionalIndex.js.map +1 -1
  51. package/dist/esm/operators/topKWithFractionalIndexBTree.d.ts +2 -1
  52. package/dist/esm/utils.d.ts +6 -0
  53. package/dist/esm/utils.js +13 -1
  54. package/dist/esm/utils.js.map +1 -1
  55. package/package.json +1 -1
  56. package/src/index.ts +1 -1
  57. package/src/operators/groupBy.ts +2 -1
  58. package/src/operators/groupedOrderBy.ts +95 -0
  59. package/src/operators/groupedTopKWithFractionalIndex.ts +192 -0
  60. package/src/operators/index.ts +2 -0
  61. package/src/operators/topKArray.ts +255 -0
  62. package/src/operators/topKState.ts +111 -0
  63. package/src/operators/topKWithFractionalIndex.ts +13 -337
  64. package/src/operators/topKWithFractionalIndexBTree.ts +4 -12
  65. package/src/utils.ts +17 -0
@@ -0,0 +1,192 @@
1
+ import { DifferenceStreamWriter, UnaryOperator } from '../graph.js'
2
+ import { StreamBuilder } from '../d2.js'
3
+ import { MultiSet } from '../multiset.js'
4
+ import { TopKState, handleMoveIn, handleMoveOut } from './topKState.js'
5
+ import { TopKArray, createKeyedComparator } from './topKArray.js'
6
+ import type { IndexedValue, TopK } from './topKArray.js'
7
+ import type { DifferenceStreamReader } from '../graph.js'
8
+ import type { IStreamBuilder, PipedOperator } from '../types.js'
9
+
10
+ export interface GroupedTopKWithFractionalIndexOptions<K, T> {
11
+ limit?: number
12
+ offset?: number
13
+ setSizeCallback?: (getSize: () => number) => void
14
+ setWindowFn?: (
15
+ windowFn: (options: { offset?: number; limit?: number }) => void,
16
+ ) => void
17
+ /**
18
+ * Function to extract a group key from the element's key and value.
19
+ * Elements with the same group key will be sorted and limited together.
20
+ */
21
+ groupKeyFn: (key: K, value: T) => unknown
22
+ }
23
+
24
+ /**
25
+ * Operator for grouped fractional indexed topK operations.
26
+ * This operator maintains separate topK windows for each group,
27
+ * allowing per-group limits and ordering.
28
+ *
29
+ * The input is a keyed stream [K, T] and outputs [K, IndexedValue<T>].
30
+ * Elements are grouped by the groupKeyFn, and each group maintains
31
+ * its own sorted collection with independent limit/offset.
32
+ */
33
+ export class GroupedTopKWithFractionalIndexOperator<
34
+ K extends string | number,
35
+ T,
36
+ > extends UnaryOperator<[K, T], [K, IndexedValue<T>]> {
37
+ #groupStates: Map<unknown, TopKState<K, T>> = new Map()
38
+ #groupKeyFn: (key: K, value: T) => unknown
39
+ #comparator: (a: [K, T], b: [K, T]) => number
40
+ #offset: number
41
+ #limit: number
42
+
43
+ constructor(
44
+ id: number,
45
+ inputA: DifferenceStreamReader<[K, T]>,
46
+ output: DifferenceStreamWriter<[K, IndexedValue<T>]>,
47
+ comparator: (a: T, b: T) => number,
48
+ options: GroupedTopKWithFractionalIndexOptions<K, T>,
49
+ ) {
50
+ super(id, inputA, output)
51
+ this.#groupKeyFn = options.groupKeyFn
52
+ this.#limit = options.limit ?? Infinity
53
+ this.#offset = options.offset ?? 0
54
+ this.#comparator = createKeyedComparator(comparator)
55
+ options.setSizeCallback?.(() => this.#getTotalSize())
56
+ options.setWindowFn?.(this.#moveTopK.bind(this))
57
+ }
58
+
59
+ /**
60
+ * Creates a new TopK data structure for a group.
61
+ * Can be overridden in subclasses to use different implementations (e.g., B+ tree).
62
+ */
63
+ protected createTopK(
64
+ offset: number,
65
+ limit: number,
66
+ comparator: (a: [K, T], b: [K, T]) => number,
67
+ ): TopK<[K, T]> {
68
+ return new TopKArray(offset, limit, comparator)
69
+ }
70
+
71
+ #getTotalSize(): number {
72
+ let size = 0
73
+ for (const state of this.#groupStates.values()) {
74
+ size += state.size
75
+ }
76
+ return size
77
+ }
78
+
79
+ #getOrCreateGroupState(groupKey: unknown): TopKState<K, T> {
80
+ let state = this.#groupStates.get(groupKey)
81
+ if (!state) {
82
+ const topK = this.createTopK(this.#offset, this.#limit, this.#comparator)
83
+ state = new TopKState(topK)
84
+ this.#groupStates.set(groupKey, state)
85
+ }
86
+ return state
87
+ }
88
+
89
+ #cleanupGroupIfEmpty(groupKey: unknown, state: TopKState<K, T>): void {
90
+ if (state.isEmpty) {
91
+ this.#groupStates.delete(groupKey)
92
+ }
93
+ }
94
+
95
+ /**
96
+ * Moves the topK window for all groups based on the provided offset and limit.
97
+ * Any changes to the topK are sent to the output.
98
+ */
99
+ #moveTopK({ offset, limit }: { offset?: number; limit?: number }): void {
100
+ if (offset !== undefined) {
101
+ this.#offset = offset
102
+ }
103
+ if (limit !== undefined) {
104
+ this.#limit = limit
105
+ }
106
+
107
+ const result: Array<[[K, IndexedValue<T>], number]> = []
108
+ let hasChanges = false
109
+
110
+ for (const state of this.#groupStates.values()) {
111
+ const diff = state.move({ offset: this.#offset, limit: this.#limit }) // TODO: think we should just pass offset and limit
112
+
113
+ diff.moveIns.forEach((moveIn) => handleMoveIn(moveIn, result))
114
+ diff.moveOuts.forEach((moveOut) => handleMoveOut(moveOut, result))
115
+
116
+ if (diff.changes) {
117
+ hasChanges = true
118
+ }
119
+ }
120
+
121
+ if (hasChanges) {
122
+ this.output.sendData(new MultiSet(result))
123
+ }
124
+ }
125
+
126
+ run(): void {
127
+ const result: Array<[[K, IndexedValue<T>], number]> = []
128
+ for (const message of this.inputMessages()) {
129
+ for (const [item, multiplicity] of message.getInner()) {
130
+ const [key, value] = item
131
+ this.#processElement(key, value, multiplicity, result)
132
+ }
133
+ }
134
+
135
+ if (result.length > 0) {
136
+ this.output.sendData(new MultiSet(result))
137
+ }
138
+ }
139
+
140
+ #processElement(
141
+ key: K,
142
+ value: T,
143
+ multiplicity: number,
144
+ result: Array<[[K, IndexedValue<T>], number]>,
145
+ ): void {
146
+ const groupKey = this.#groupKeyFn(key, value)
147
+ const state = this.#getOrCreateGroupState(groupKey)
148
+
149
+ const changes = state.processElement(key, value, multiplicity)
150
+ handleMoveIn(changes.moveIn, result)
151
+ handleMoveOut(changes.moveOut, result)
152
+
153
+ // Cleanup empty groups to prevent memory leaks
154
+ this.#cleanupGroupIfEmpty(groupKey, state)
155
+ }
156
+ }
157
+
158
+ /**
159
+ * Limits the number of results per group based on a comparator, with optional offset.
160
+ * Uses fractional indexing to minimize the number of changes when elements move positions.
161
+ * Each element is assigned a fractional index that is lexicographically sortable.
162
+ * When elements move, only the indices of the moved elements are updated, not all elements.
163
+ *
164
+ * This operator groups elements by the provided groupKeyFn and applies the limit/offset
165
+ * independently to each group.
166
+ *
167
+ * @param comparator - A function that compares two elements for ordering
168
+ * @param options - Configuration including groupKeyFn, limit, and offset
169
+ * @returns A piped operator that orders elements per group and limits results per group
170
+ */
171
+ export function groupedTopKWithFractionalIndex<K extends string | number, T>(
172
+ comparator: (a: T, b: T) => number,
173
+ options: GroupedTopKWithFractionalIndexOptions<K, T>,
174
+ ): PipedOperator<[K, T], [K, IndexedValue<T>]> {
175
+ return (
176
+ stream: IStreamBuilder<[K, T]>,
177
+ ): IStreamBuilder<[K, IndexedValue<T>]> => {
178
+ const output = new StreamBuilder<[K, IndexedValue<T>]>(
179
+ stream.graph,
180
+ new DifferenceStreamWriter<[K, IndexedValue<T>]>(),
181
+ )
182
+ const operator = new GroupedTopKWithFractionalIndexOperator<K, T>(
183
+ stream.graph.getNextOperatorId(),
184
+ stream.connectReader(),
185
+ output.writer,
186
+ comparator,
187
+ options,
188
+ )
189
+ stream.graph.addOperator(operator)
190
+ return output
191
+ }
192
+ }
@@ -14,6 +14,8 @@ export * from './distinct.js'
14
14
  export * from './keying.js'
15
15
  export * from './topK.js'
16
16
  export * from './topKWithFractionalIndex.js'
17
+ export * from './groupedTopKWithFractionalIndex.js'
17
18
  export * from './orderBy.js'
19
+ export * from './groupedOrderBy.js'
18
20
  export * from './filterBy.js'
19
21
  export { groupBy, groupByOperators } from './groupBy.js'
@@ -0,0 +1,255 @@
1
+ import { generateKeyBetween } from 'fractional-indexing'
2
+ import { binarySearch, compareKeys, diffHalfOpen } from '../utils.js'
3
+ import type { HRange } from '../utils.js'
4
+
5
+ // Abstraction for fractionally indexed values
6
+ export type FractionalIndex = string
7
+ export type IndexedValue<V> = [V, FractionalIndex]
8
+
9
+ export function indexedValue<V>(
10
+ value: V,
11
+ index: FractionalIndex,
12
+ ): IndexedValue<V> {
13
+ return [value, index]
14
+ }
15
+
16
+ export function getValue<V>(indexedVal: IndexedValue<V>): V {
17
+ return indexedVal[0]
18
+ }
19
+
20
+ export 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
+ */
28
+ export 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
+
43
+ export 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
+
50
+ export 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
+ */
63
+ export interface TopK<V> {
64
+ size: number
65
+ insert: (value: V) => TopKChanges<V>
66
+ delete: (value: V) => TopKChanges<V>
67
+ }
68
+
69
+ /**
70
+ * Implementation of a topK data structure.
71
+ * Uses a sorted array internally to store the values and keeps a topK window over that array.
72
+ * Inserts and deletes are O(n) operations because worst case an element is inserted/deleted
73
+ * at the start of the array which causes all the elements to shift to the right/left.
74
+ */
75
+ export class TopKArray<V> implements TopK<V> {
76
+ #sortedValues: Array<IndexedValue<V>> = []
77
+ #comparator: (a: V, b: V) => number
78
+ #topKStart: number
79
+ #topKEnd: number
80
+
81
+ constructor(
82
+ offset: number,
83
+ limit: number,
84
+ comparator: (a: V, b: V) => number,
85
+ ) {
86
+ this.#topKStart = offset
87
+ this.#topKEnd = offset + limit
88
+ this.#comparator = comparator
89
+ }
90
+
91
+ get size(): number {
92
+ const offset = this.#topKStart
93
+ const limit = this.#topKEnd - this.#topKStart
94
+ const available = this.#sortedValues.length - offset
95
+ return Math.max(0, Math.min(limit, available))
96
+ }
97
+
98
+ /**
99
+ * Moves the topK window
100
+ */
101
+ move({
102
+ offset,
103
+ limit,
104
+ }: {
105
+ offset?: number
106
+ limit?: number
107
+ }): TopKMoveChanges<V> {
108
+ const oldOffset = this.#topKStart
109
+ const oldLimit = this.#topKEnd - this.#topKStart
110
+
111
+ // `this.#topKEnd` can be `Infinity` if it has no limit
112
+ // but `diffHalfOpen` expects a finite range
113
+ // so we restrict it to the size of the topK if topKEnd is infinite
114
+ const oldRange: HRange = [
115
+ this.#topKStart,
116
+ this.#topKEnd === Infinity ? this.#topKStart + this.size : this.#topKEnd,
117
+ ]
118
+
119
+ this.#topKStart = offset ?? oldOffset
120
+ this.#topKEnd = this.#topKStart + (limit ?? oldLimit) // can be `Infinity` if limit is `Infinity`
121
+
122
+ // Also handle `Infinity` in the newRange
123
+ const newRange: HRange = [
124
+ this.#topKStart,
125
+ this.#topKEnd === Infinity
126
+ ? 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)
127
+ : this.#topKEnd,
128
+ ]
129
+ const { onlyInA, onlyInB } = diffHalfOpen(oldRange, newRange)
130
+
131
+ const moveIns: Array<IndexedValue<V>> = []
132
+ onlyInB.forEach((index) => {
133
+ const value = this.#sortedValues[index]
134
+ if (value) {
135
+ moveIns.push(value)
136
+ }
137
+ })
138
+
139
+ const moveOuts: Array<IndexedValue<V>> = []
140
+ onlyInA.forEach((index) => {
141
+ const value = this.#sortedValues[index]
142
+ if (value) {
143
+ moveOuts.push(value)
144
+ }
145
+ })
146
+
147
+ // It could be that there are changes (i.e. moveIns or moveOuts)
148
+ // but that the collection is lazy so we don't have the data yet that needs to move in/out
149
+ // so `moveIns` and `moveOuts` will be empty but `changes` will be true
150
+ // this will tell the caller that it needs to run the graph to load more data
151
+ return { moveIns, moveOuts, changes: onlyInA.length + onlyInB.length > 0 }
152
+ }
153
+
154
+ insert(value: V): TopKChanges<V> {
155
+ const result: TopKChanges<V> = { moveIn: null, moveOut: null }
156
+
157
+ // Lookup insert position
158
+ const index = this.#findIndex(value)
159
+ // Generate fractional index based on the fractional indices of the elements before and after it
160
+ const indexBefore =
161
+ index === 0 ? null : getIndex(this.#sortedValues[index - 1]!)
162
+ const indexAfter =
163
+ index === this.#sortedValues.length
164
+ ? null
165
+ : getIndex(this.#sortedValues[index]!)
166
+ const fractionalIndex = generateKeyBetween(indexBefore, indexAfter)
167
+
168
+ // Insert the value at the correct position
169
+ const val = indexedValue(value, fractionalIndex)
170
+ // Splice is O(n) where n = all elements in the collection (i.e. n >= k) !
171
+ this.#sortedValues.splice(index, 0, val)
172
+
173
+ // Check if the topK changed
174
+ if (index < this.#topKEnd) {
175
+ // The inserted element is either before the top K or within the top K
176
+ // If it is before the top K then it moves the element that was right before the topK into the topK
177
+ // If it is within the top K then the inserted element moves into the top K
178
+ // In both cases the last element of the old top K now moves out of the top K
179
+ const moveInIndex = Math.max(index, this.#topKStart)
180
+ if (moveInIndex < this.#sortedValues.length) {
181
+ // We actually have a topK
182
+ // because in some cases there may not be enough elements in the array to reach the start of the topK
183
+ // e.g. [1, 2, 3] with K = 2 and offset = 3 does not have a topK
184
+ result.moveIn = this.#sortedValues[moveInIndex]!
185
+
186
+ // We need to remove the element that falls out of the top K
187
+ // The element that falls out of the top K has shifted one to the right
188
+ // because of the element we inserted, so we find it at index topKEnd
189
+ if (this.#topKEnd < this.#sortedValues.length) {
190
+ result.moveOut = this.#sortedValues[this.#topKEnd]!
191
+ }
192
+ }
193
+ }
194
+
195
+ return result
196
+ }
197
+
198
+ /**
199
+ * Deletes a value that may or may not be in the topK.
200
+ * IMPORTANT: this assumes that the value is present in the collection
201
+ * if it's not the case it will remove the element
202
+ * that is on the position where the provided `value` would be.
203
+ */
204
+ delete(value: V): TopKChanges<V> {
205
+ const result: TopKChanges<V> = { moveIn: null, moveOut: null }
206
+
207
+ // Lookup delete position
208
+ const index = this.#findIndex(value)
209
+ // Remove the value at that position
210
+ const [removedElem] = this.#sortedValues.splice(index, 1)
211
+
212
+ // Check if the topK changed
213
+ if (index < this.#topKEnd) {
214
+ // The removed element is either before the top K or within the top K
215
+ // If it is before the top K then the first element of the topK moves out of the topK
216
+ // If it is within the top K then the removed element moves out of the topK
217
+ result.moveOut = removedElem!
218
+ if (index < this.#topKStart) {
219
+ // The removed element is before the topK
220
+ // so actually, the first element of the topK moves out of the topK
221
+ // and not the element that we removed
222
+ // The first element of the topK is now at index topKStart - 1
223
+ // since we removed an element before the topK
224
+ const moveOutIndex = this.#topKStart - 1
225
+ if (moveOutIndex < this.#sortedValues.length) {
226
+ result.moveOut = this.#sortedValues[moveOutIndex]!
227
+ } else {
228
+ // No value is moving out of the topK
229
+ // because there are no elements in the topK
230
+ result.moveOut = null
231
+ }
232
+ }
233
+
234
+ // Since we removed an element that was before or in the topK
235
+ // the first element after the topK moved one position to the left
236
+ // and thus falls into the topK now
237
+ const moveInIndex = this.#topKEnd - 1
238
+ if (moveInIndex < this.#sortedValues.length) {
239
+ result.moveIn = this.#sortedValues[moveInIndex]!
240
+ }
241
+ }
242
+
243
+ return result
244
+ }
245
+
246
+ // TODO: see if there is a way to refactor the code for insert and delete in the topK above
247
+ // because they are very similar, one is shifting the topK window to the left and the other is shifting it to the right
248
+ // so i have the feeling there is a common pattern here and we can implement both cases using that pattern
249
+
250
+ #findIndex(value: V): number {
251
+ return binarySearch(this.#sortedValues, indexedValue(value, ``), (a, b) =>
252
+ this.#comparator(getValue(a), getValue(b)),
253
+ )
254
+ }
255
+ }
@@ -0,0 +1,111 @@
1
+ import { TopKArray } from './topKArray.js'
2
+ import type {
3
+ IndexedValue,
4
+ TopK,
5
+ TopKChanges,
6
+ TopKMoveChanges,
7
+ } from './topKArray.js'
8
+
9
+ /**
10
+ * Helper class that manages the state for a single topK window.
11
+ * Encapsulates the multiplicity tracking and topK data structure,
12
+ * providing a clean interface for processing elements and moving the window.
13
+ *
14
+ * This class is used by both TopKWithFractionalIndexOperator (single instance)
15
+ * and GroupedTopKWithFractionalIndexOperator (one instance per group).
16
+ */
17
+ export class TopKState<K extends string | number, T> {
18
+ #multiplicities: Map<K, number> = new Map()
19
+ #topK: TopK<[K, T]>
20
+
21
+ constructor(topK: TopK<[K, T]>) {
22
+ this.#topK = topK
23
+ }
24
+
25
+ get size(): number {
26
+ return this.#topK.size
27
+ }
28
+
29
+ get isEmpty(): boolean {
30
+ return this.#multiplicities.size === 0 && this.#topK.size === 0
31
+ }
32
+
33
+ /**
34
+ * Process an element update (insert or delete based on multiplicity change).
35
+ * Returns the changes to the topK window.
36
+ */
37
+ processElement(key: K, value: T, multiplicity: number): TopKChanges<[K, T]> {
38
+ const { oldMultiplicity, newMultiplicity } = this.#updateMultiplicity(
39
+ key,
40
+ multiplicity,
41
+ )
42
+
43
+ if (oldMultiplicity <= 0 && newMultiplicity > 0) {
44
+ // The value was invisible but should now be visible
45
+ return this.#topK.insert([key, value])
46
+ } else if (oldMultiplicity > 0 && newMultiplicity <= 0) {
47
+ // The value was visible but should now be invisible
48
+ return this.#topK.delete([key, value])
49
+ }
50
+ // The value was invisible and remains invisible,
51
+ // or was visible and remains visible - no topK change
52
+ return { moveIn: null, moveOut: null }
53
+ }
54
+
55
+ /**
56
+ * Move the topK window. Only works with TopKArray implementation.
57
+ */
58
+ move(options: { offset?: number; limit?: number }): TopKMoveChanges<[K, T]> {
59
+ if (!(this.#topK instanceof TopKArray)) {
60
+ throw new Error(
61
+ `Cannot move B+-tree implementation of TopK with fractional index`,
62
+ )
63
+ }
64
+ return this.#topK.move(options)
65
+ }
66
+
67
+ #updateMultiplicity(
68
+ key: K,
69
+ multiplicity: number,
70
+ ): { oldMultiplicity: number; newMultiplicity: number } {
71
+ if (multiplicity === 0) {
72
+ const current = this.#multiplicities.get(key) ?? 0
73
+ return { oldMultiplicity: current, newMultiplicity: current }
74
+ }
75
+
76
+ const oldMultiplicity = this.#multiplicities.get(key) ?? 0
77
+ const newMultiplicity = oldMultiplicity + multiplicity
78
+ if (newMultiplicity === 0) {
79
+ this.#multiplicities.delete(key)
80
+ } else {
81
+ this.#multiplicities.set(key, newMultiplicity)
82
+ }
83
+ return { oldMultiplicity, newMultiplicity }
84
+ }
85
+ }
86
+
87
+ /**
88
+ * Handles a moveIn change by adding it to the result array.
89
+ */
90
+ export function handleMoveIn<K extends string | number, T>(
91
+ moveIn: IndexedValue<[K, T]> | null,
92
+ result: Array<[[K, IndexedValue<T>], number]>,
93
+ ): void {
94
+ if (moveIn) {
95
+ const [[key, value], index] = moveIn
96
+ result.push([[key, [value, index]], 1])
97
+ }
98
+ }
99
+
100
+ /**
101
+ * Handles a moveOut change by adding it to the result array.
102
+ */
103
+ export function handleMoveOut<K extends string | number, T>(
104
+ moveOut: IndexedValue<[K, T]> | null,
105
+ result: Array<[[K, IndexedValue<T>], number]>,
106
+ ): void {
107
+ if (moveOut) {
108
+ const [[key, value], index] = moveOut
109
+ result.push([[key, [value, index]], -1])
110
+ }
111
+ }