@tanstack/db-ivm 0.1.13 → 0.1.15

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 (126) hide show
  1. package/README.md +3 -3
  2. package/dist/cjs/d2.cjs.map +1 -1
  3. package/dist/cjs/graph.cjs.map +1 -1
  4. package/dist/cjs/hashing/hash.cjs.map +1 -1
  5. package/dist/cjs/index.cjs +6 -3
  6. package/dist/cjs/index.cjs.map +1 -1
  7. package/dist/cjs/index.d.cts +1 -0
  8. package/dist/cjs/indexes.cjs +1 -1
  9. package/dist/cjs/indexes.cjs.map +1 -1
  10. package/dist/cjs/multiset.cjs.map +1 -1
  11. package/dist/cjs/operators/concat.cjs.map +1 -1
  12. package/dist/cjs/operators/consolidate.cjs.map +1 -1
  13. package/dist/cjs/operators/count.cjs.map +1 -1
  14. package/dist/cjs/operators/debug.cjs.map +1 -1
  15. package/dist/cjs/operators/distinct.cjs.map +1 -1
  16. package/dist/cjs/operators/filter.cjs.map +1 -1
  17. package/dist/cjs/operators/filterBy.cjs.map +1 -1
  18. package/dist/cjs/operators/groupBy.cjs +2 -1
  19. package/dist/cjs/operators/groupBy.cjs.map +1 -1
  20. package/dist/cjs/operators/groupedTopKWithFractionalIndex.cjs +116 -0
  21. package/dist/cjs/operators/groupedTopKWithFractionalIndex.cjs.map +1 -0
  22. package/dist/cjs/operators/groupedTopKWithFractionalIndex.d.cts +50 -0
  23. package/dist/cjs/operators/index.d.cts +1 -0
  24. package/dist/cjs/operators/join.cjs.map +1 -1
  25. package/dist/cjs/operators/keying.cjs.map +1 -1
  26. package/dist/cjs/operators/map.cjs.map +1 -1
  27. package/dist/cjs/operators/negate.cjs.map +1 -1
  28. package/dist/cjs/operators/orderBy.cjs.map +1 -1
  29. package/dist/cjs/operators/output.cjs.map +1 -1
  30. package/dist/cjs/operators/pipe.cjs.map +1 -1
  31. package/dist/cjs/operators/reduce.cjs.map +1 -1
  32. package/dist/cjs/operators/tap.cjs.map +1 -1
  33. package/dist/cjs/operators/topK.cjs.map +1 -1
  34. package/dist/cjs/operators/topKArray.cjs +137 -0
  35. package/dist/cjs/operators/topKArray.cjs.map +1 -0
  36. package/dist/cjs/operators/topKArray.d.cts +59 -0
  37. package/dist/cjs/operators/topKState.cjs +73 -0
  38. package/dist/cjs/operators/topKState.cjs.map +1 -0
  39. package/dist/cjs/operators/topKState.d.cts +35 -0
  40. package/dist/cjs/operators/topKWithFractionalIndex.cjs +17 -208
  41. package/dist/cjs/operators/topKWithFractionalIndex.cjs.map +1 -1
  42. package/dist/cjs/operators/topKWithFractionalIndex.d.cts +4 -43
  43. package/dist/cjs/operators/topKWithFractionalIndexBTree.d.cts +5 -4
  44. package/dist/cjs/utils.cjs +21 -0
  45. package/dist/cjs/utils.cjs.map +1 -1
  46. package/dist/cjs/utils.d.cts +11 -0
  47. package/dist/esm/d2.js.map +1 -1
  48. package/dist/esm/graph.js.map +1 -1
  49. package/dist/esm/hashing/hash.js.map +1 -1
  50. package/dist/esm/index.d.ts +1 -0
  51. package/dist/esm/index.js +7 -4
  52. package/dist/esm/index.js.map +1 -1
  53. package/dist/esm/indexes.js +1 -1
  54. package/dist/esm/indexes.js.map +1 -1
  55. package/dist/esm/multiset.js.map +1 -1
  56. package/dist/esm/operators/concat.js.map +1 -1
  57. package/dist/esm/operators/consolidate.js.map +1 -1
  58. package/dist/esm/operators/count.js.map +1 -1
  59. package/dist/esm/operators/debug.js.map +1 -1
  60. package/dist/esm/operators/distinct.js.map +1 -1
  61. package/dist/esm/operators/filter.js.map +1 -1
  62. package/dist/esm/operators/filterBy.js.map +1 -1
  63. package/dist/esm/operators/groupBy.js +2 -1
  64. package/dist/esm/operators/groupBy.js.map +1 -1
  65. package/dist/esm/operators/groupedTopKWithFractionalIndex.d.ts +50 -0
  66. package/dist/esm/operators/groupedTopKWithFractionalIndex.js +116 -0
  67. package/dist/esm/operators/groupedTopKWithFractionalIndex.js.map +1 -0
  68. package/dist/esm/operators/index.d.ts +1 -0
  69. package/dist/esm/operators/join.js.map +1 -1
  70. package/dist/esm/operators/keying.js.map +1 -1
  71. package/dist/esm/operators/map.js.map +1 -1
  72. package/dist/esm/operators/negate.js.map +1 -1
  73. package/dist/esm/operators/orderBy.js.map +1 -1
  74. package/dist/esm/operators/output.js.map +1 -1
  75. package/dist/esm/operators/pipe.js.map +1 -1
  76. package/dist/esm/operators/reduce.js.map +1 -1
  77. package/dist/esm/operators/tap.js.map +1 -1
  78. package/dist/esm/operators/topK.js.map +1 -1
  79. package/dist/esm/operators/topKArray.d.ts +59 -0
  80. package/dist/esm/operators/topKArray.js +137 -0
  81. package/dist/esm/operators/topKArray.js.map +1 -0
  82. package/dist/esm/operators/topKState.d.ts +35 -0
  83. package/dist/esm/operators/topKState.js +73 -0
  84. package/dist/esm/operators/topKState.js.map +1 -0
  85. package/dist/esm/operators/topKWithFractionalIndex.d.ts +4 -43
  86. package/dist/esm/operators/topKWithFractionalIndex.js +16 -207
  87. package/dist/esm/operators/topKWithFractionalIndex.js.map +1 -1
  88. package/dist/esm/operators/topKWithFractionalIndexBTree.d.ts +5 -4
  89. package/dist/esm/utils.d.ts +11 -0
  90. package/dist/esm/utils.js +22 -1
  91. package/dist/esm/utils.js.map +1 -1
  92. package/package.json +29 -29
  93. package/src/d2.ts +4 -4
  94. package/src/graph.ts +6 -6
  95. package/src/hashing/hash.ts +3 -3
  96. package/src/hashing/index.ts +2 -2
  97. package/src/index.ts +5 -4
  98. package/src/indexes.ts +8 -8
  99. package/src/multiset.ts +5 -5
  100. package/src/operators/concat.ts +6 -6
  101. package/src/operators/consolidate.ts +6 -6
  102. package/src/operators/count.ts +9 -9
  103. package/src/operators/debug.ts +8 -8
  104. package/src/operators/distinct.ts +11 -11
  105. package/src/operators/filter.ts +8 -8
  106. package/src/operators/filterBy.ts +7 -7
  107. package/src/operators/groupBy.ts +24 -23
  108. package/src/operators/groupedTopKWithFractionalIndex.ts +192 -0
  109. package/src/operators/index.ts +20 -19
  110. package/src/operators/join.ts +23 -23
  111. package/src/operators/keying.ts +4 -4
  112. package/src/operators/map.ts +8 -8
  113. package/src/operators/negate.ts +6 -6
  114. package/src/operators/orderBy.ts +26 -26
  115. package/src/operators/orderByBTree.ts +7 -7
  116. package/src/operators/output.ts +9 -9
  117. package/src/operators/pipe.ts +1 -1
  118. package/src/operators/reduce.ts +9 -9
  119. package/src/operators/tap.ts +8 -8
  120. package/src/operators/topK.ts +8 -8
  121. package/src/operators/topKArray.ts +255 -0
  122. package/src/operators/topKState.ts +111 -0
  123. package/src/operators/topKWithFractionalIndex.ts +36 -381
  124. package/src/operators/topKWithFractionalIndexBTree.ts +21 -30
  125. package/src/types.ts +22 -22
  126. package/src/utils.ts +36 -4
@@ -1,8 +1,8 @@
1
- import { DifferenceStreamWriter, UnaryOperator } from "../graph.js"
2
- import { StreamBuilder } from "../d2.js"
3
- import type { IStreamBuilder, PipedOperator } from "../types.js"
4
- import type { DifferenceStreamReader } from "../graph.js"
5
- import type { MultiSet } from "../multiset.js"
1
+ import { DifferenceStreamWriter, UnaryOperator } from '../graph.js'
2
+ import { StreamBuilder } from '../d2.js'
3
+ import type { IStreamBuilder, PipedOperator } from '../types.js'
4
+ import type { DifferenceStreamReader } from '../graph.js'
5
+ import type { MultiSet } from '../multiset.js'
6
6
 
7
7
  /**
8
8
  * Operator that outputs the messages in the stream
@@ -14,7 +14,7 @@ export class OutputOperator<T> extends UnaryOperator<T> {
14
14
  id: number,
15
15
  inputA: DifferenceStreamReader<T>,
16
16
  outputWriter: DifferenceStreamWriter<T>,
17
- fn: (data: MultiSet<T>) => void
17
+ fn: (data: MultiSet<T>) => void,
18
18
  ) {
19
19
  super(id, inputA, outputWriter)
20
20
  this.#fn = fn
@@ -33,18 +33,18 @@ export class OutputOperator<T> extends UnaryOperator<T> {
33
33
  * @param fn - The function to call with each message
34
34
  */
35
35
  export function output<T>(
36
- fn: (data: MultiSet<T>) => void
36
+ fn: (data: MultiSet<T>) => void,
37
37
  ): PipedOperator<T, T> {
38
38
  return (stream: IStreamBuilder<T>): IStreamBuilder<T> => {
39
39
  const outputStream = new StreamBuilder<T>(
40
40
  stream.graph,
41
- new DifferenceStreamWriter<T>()
41
+ new DifferenceStreamWriter<T>(),
42
42
  )
43
43
  const operator = new OutputOperator<T>(
44
44
  stream.graph.getNextOperatorId(),
45
45
  stream.connectReader(),
46
46
  outputStream.writer,
47
- fn
47
+ fn,
48
48
  )
49
49
  stream.graph.addOperator(operator)
50
50
  return outputStream
@@ -1,4 +1,4 @@
1
- import type { IStreamBuilder, PipedOperator } from "../types.js"
1
+ import type { IStreamBuilder, PipedOperator } from '../types.js'
2
2
 
3
3
  // Don't judge, this is the only way to type this function.
4
4
  // rxjs has very similar code to type its pipe function
@@ -1,9 +1,9 @@
1
- import { DifferenceStreamWriter, UnaryOperator } from "../graph.js"
2
- import { StreamBuilder } from "../d2.js"
3
- import { MultiSet } from "../multiset.js"
4
- import { Index } from "../indexes.js"
5
- import type { DifferenceStreamReader } from "../graph.js"
6
- import type { IStreamBuilder, KeyValue } from "../types.js"
1
+ import { DifferenceStreamWriter, UnaryOperator } from '../graph.js'
2
+ import { StreamBuilder } from '../d2.js'
3
+ import { MultiSet } from '../multiset.js'
4
+ import { Index } from '../indexes.js'
5
+ import type { DifferenceStreamReader } from '../graph.js'
6
+ import type { IStreamBuilder, KeyValue } from '../types.js'
7
7
 
8
8
  /**
9
9
  * Base operator for reduction operations (version-free)
@@ -17,7 +17,7 @@ export class ReduceOperator<K, V1, V2> extends UnaryOperator<[K, V1], [K, V2]> {
17
17
  id: number,
18
18
  inputA: DifferenceStreamReader<[K, V1]>,
19
19
  output: DifferenceStreamWriter<[K, V2]>,
20
- f: (values: Array<[V1, number]>) => Array<[V2, number]>
20
+ f: (values: Array<[V1, number]>) => Array<[V2, number]>,
21
21
  ) {
22
22
  super(id, inputA, output)
23
23
  this.#f = f
@@ -109,13 +109,13 @@ export function reduce<
109
109
  return (stream: IStreamBuilder<T>): IStreamBuilder<KeyValue<KType, R>> => {
110
110
  const output = new StreamBuilder<KeyValue<KType, R>>(
111
111
  stream.graph,
112
- new DifferenceStreamWriter<KeyValue<KType, R>>()
112
+ new DifferenceStreamWriter<KeyValue<KType, R>>(),
113
113
  )
114
114
  const operator = new ReduceOperator<KType, V1Type, R>(
115
115
  stream.graph.getNextOperatorId(),
116
116
  stream.connectReader() as DifferenceStreamReader<KeyValue<KType, V1Type>>,
117
117
  output.writer,
118
- f
118
+ f,
119
119
  )
120
120
  stream.graph.addOperator(operator)
121
121
  return output
@@ -1,8 +1,8 @@
1
- import { DifferenceStreamWriter, LinearUnaryOperator } from "../graph.js"
2
- import { StreamBuilder } from "../d2.js"
3
- import type { IStreamBuilder, PipedOperator } from "../types.js"
4
- import type { DifferenceStreamReader } from "../graph.js"
5
- import type { MultiSet } from "../multiset.js"
1
+ import { DifferenceStreamWriter, LinearUnaryOperator } from '../graph.js'
2
+ import { StreamBuilder } from '../d2.js'
3
+ import type { IStreamBuilder, PipedOperator } from '../types.js'
4
+ import type { DifferenceStreamReader } from '../graph.js'
5
+ import type { MultiSet } from '../multiset.js'
6
6
 
7
7
  /**
8
8
  * Operator that applies a function to each multi-set in the input stream
@@ -14,7 +14,7 @@ export class TapOperator<T> extends LinearUnaryOperator<T, T> {
14
14
  id: number,
15
15
  inputA: DifferenceStreamReader<T>,
16
16
  output: DifferenceStreamWriter<T>,
17
- f: (data: MultiSet<T>) => void
17
+ f: (data: MultiSet<T>) => void,
18
18
  ) {
19
19
  super(id, inputA, output)
20
20
  this.#f = f
@@ -36,13 +36,13 @@ export function tap<T>(f: (data: MultiSet<T>) => void): PipedOperator<T, T> {
36
36
  return (stream: IStreamBuilder<T>): IStreamBuilder<T> => {
37
37
  const output = new StreamBuilder<T>(
38
38
  stream.graph,
39
- new DifferenceStreamWriter<T>()
39
+ new DifferenceStreamWriter<T>(),
40
40
  )
41
41
  const operator = new TapOperator<T>(
42
42
  stream.graph.getNextOperatorId(),
43
43
  stream.connectReader(),
44
44
  output.writer,
45
- f
45
+ f,
46
46
  )
47
47
  stream.graph.addOperator(operator)
48
48
  return output
@@ -1,6 +1,6 @@
1
- import { MultiSet } from "../multiset.js"
2
- import { reduce } from "./reduce.js"
3
- import type { IStreamBuilder, KeyValue, PipedOperator } from "../types"
1
+ import { MultiSet } from '../multiset.js'
2
+ import { reduce } from './reduce.js'
3
+ import type { IStreamBuilder, KeyValue, PipedOperator } from '../types'
4
4
 
5
5
  interface TopKOptions {
6
6
  limit?: number
@@ -24,7 +24,7 @@ export function topK<
24
24
  T,
25
25
  >(
26
26
  comparator: (a: V1Type, b: V1Type) => number,
27
- options?: TopKOptions
27
+ options?: TopKOptions,
28
28
  ): PipedOperator<T, T> {
29
29
  const limit = options?.limit ?? Infinity
30
30
  const offset = options?.offset ?? 0
@@ -38,7 +38,7 @@ export function topK<
38
38
  .getInner()
39
39
  .sort((a, b) => comparator(a[0] as V1Type, b[0] as V1Type))
40
40
  return sortedValues.slice(offset, offset + limit)
41
- })
41
+ }),
42
42
  )
43
43
  return reduced as IStreamBuilder<T>
44
44
  }
@@ -62,13 +62,13 @@ export function topKWithIndex<
62
62
  T,
63
63
  >(
64
64
  comparator: (a: V1Type, b: V1Type) => number,
65
- options?: TopKOptions
65
+ options?: TopKOptions,
66
66
  ): PipedOperator<T, KeyValue<KType, [V1Type, number]>> {
67
67
  const limit = options?.limit ?? Infinity
68
68
  const offset = options?.offset ?? 0
69
69
 
70
70
  return (
71
- stream: IStreamBuilder<T>
71
+ stream: IStreamBuilder<T>,
72
72
  ): IStreamBuilder<KeyValue<KType, [V1Type, number]>> => {
73
73
  const reduced = stream.pipe(
74
74
  reduce<KType, V1Type, [V1Type, number], T>((values) => {
@@ -84,7 +84,7 @@ export function topKWithIndex<
84
84
  multiplicity,
85
85
  ])
86
86
  return sortedValues
87
- })
87
+ }),
88
88
  )
89
89
  return reduced
90
90
  }
@@ -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
+ }