@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,140 +1,21 @@
1
- import { generateKeyBetween } from "fractional-indexing";
2
1
  import { UnaryOperator, DifferenceStreamWriter } from "../graph.js";
3
2
  import { StreamBuilder } from "../d2.js";
4
3
  import { MultiSet } from "../multiset.js";
5
- import { diffHalfOpen, binarySearch, globalObjectIdGenerator } from "../utils.js";
6
- class TopKArray {
7
- #sortedValues = [];
8
- #comparator;
9
- #topKStart;
10
- #topKEnd;
11
- constructor(offset, limit, comparator) {
12
- this.#topKStart = offset;
13
- this.#topKEnd = offset + limit;
14
- this.#comparator = comparator;
15
- }
16
- get size() {
17
- const offset = this.#topKStart;
18
- const limit = this.#topKEnd - this.#topKStart;
19
- const available = this.#sortedValues.length - offset;
20
- return Math.max(0, Math.min(limit, available));
21
- }
22
- /**
23
- * Moves the topK window
24
- */
25
- move({
26
- offset,
27
- limit
28
- }) {
29
- const oldOffset = this.#topKStart;
30
- const oldLimit = this.#topKEnd - this.#topKStart;
31
- const oldRange = [
32
- this.#topKStart,
33
- this.#topKEnd === Infinity ? this.#topKStart + this.size : this.#topKEnd
34
- ];
35
- this.#topKStart = offset ?? oldOffset;
36
- this.#topKEnd = this.#topKStart + (limit ?? oldLimit);
37
- const newRange = [
38
- this.#topKStart,
39
- this.#topKEnd === Infinity ? Math.max(this.#topKStart + this.size, oldRange[1]) : this.#topKEnd
40
- ];
41
- const { onlyInA, onlyInB } = diffHalfOpen(oldRange, newRange);
42
- const moveIns = [];
43
- onlyInB.forEach((index) => {
44
- const value = this.#sortedValues[index];
45
- if (value) {
46
- moveIns.push(value);
47
- }
48
- });
49
- const moveOuts = [];
50
- onlyInA.forEach((index) => {
51
- const value = this.#sortedValues[index];
52
- if (value) {
53
- moveOuts.push(value);
54
- }
55
- });
56
- return { moveIns, moveOuts, changes: onlyInA.length + onlyInB.length > 0 };
57
- }
58
- insert(value) {
59
- const result = { moveIn: null, moveOut: null };
60
- const index = this.#findIndex(value);
61
- const indexBefore = index === 0 ? null : getIndex(this.#sortedValues[index - 1]);
62
- const indexAfter = index === this.#sortedValues.length ? null : getIndex(this.#sortedValues[index]);
63
- const fractionalIndex = generateKeyBetween(indexBefore, indexAfter);
64
- const val = indexedValue(value, fractionalIndex);
65
- this.#sortedValues.splice(index, 0, val);
66
- if (index < this.#topKEnd) {
67
- const moveInIndex = Math.max(index, this.#topKStart);
68
- if (moveInIndex < this.#sortedValues.length) {
69
- result.moveIn = this.#sortedValues[moveInIndex];
70
- if (this.#topKEnd < this.#sortedValues.length) {
71
- result.moveOut = this.#sortedValues[this.#topKEnd];
72
- }
73
- }
74
- }
75
- return result;
76
- }
77
- /**
78
- * Deletes a value that may or may not be in the topK.
79
- * IMPORTANT: this assumes that the value is present in the collection
80
- * if it's not the case it will remove the element
81
- * that is on the position where the provided `value` would be.
82
- */
83
- delete(value) {
84
- const result = { moveIn: null, moveOut: null };
85
- const index = this.#findIndex(value);
86
- const [removedElem] = this.#sortedValues.splice(index, 1);
87
- if (index < this.#topKEnd) {
88
- result.moveOut = removedElem;
89
- if (index < this.#topKStart) {
90
- const moveOutIndex = this.#topKStart - 1;
91
- if (moveOutIndex < this.#sortedValues.length) {
92
- result.moveOut = this.#sortedValues[moveOutIndex];
93
- } else {
94
- result.moveOut = null;
95
- }
96
- }
97
- const moveInIndex = this.#topKEnd - 1;
98
- if (moveInIndex < this.#sortedValues.length) {
99
- result.moveIn = this.#sortedValues[moveInIndex];
100
- }
101
- }
102
- return result;
103
- }
104
- // TODO: see if there is a way to refactor the code for insert and delete in the topK above
105
- // because they are very similar, one is shifting the topK window to the left and the other is shifting it to the right
106
- // so i have the feeling there is a common pattern here and we can implement both cases using that pattern
107
- #findIndex(value) {
108
- return binarySearch(
109
- this.#sortedValues,
110
- indexedValue(value, ``),
111
- (a, b) => this.#comparator(getValue(a), getValue(b))
112
- );
113
- }
114
- }
4
+ import { TopKState, handleMoveIn, handleMoveOut } from "./topKState.js";
5
+ import { createKeyedComparator, TopKArray } from "./topKArray.js";
115
6
  class TopKWithFractionalIndexOperator extends UnaryOperator {
116
- #index = /* @__PURE__ */ new Map();
117
- // maps keys to their multiplicity
118
- /**
119
- * topK data structure that supports insertions and deletions
120
- * and returns changes to the topK.
121
- */
122
- #topK;
7
+ #state;
123
8
  constructor(id, inputA, output, comparator, options) {
124
9
  super(id, inputA, output);
125
10
  const limit = options.limit ?? Infinity;
126
11
  const offset = options.offset ?? 0;
127
- const compareTaggedValues = (a, b) => {
128
- const valueComparison = comparator(getVal(a), getVal(b));
129
- if (valueComparison !== 0) {
130
- return valueComparison;
131
- }
132
- const tieBreakerA = getTag(a);
133
- const tieBreakerB = getTag(b);
134
- return tieBreakerA - tieBreakerB;
135
- };
136
- this.#topK = this.createTopK(offset, limit, compareTaggedValues);
137
- options.setSizeCallback?.(() => this.#topK.size);
12
+ const topK = this.createTopK(
13
+ offset,
14
+ limit,
15
+ createKeyedComparator(comparator)
16
+ );
17
+ this.#state = new TopKState(topK);
18
+ options.setSizeCallback?.(() => this.#state.size);
138
19
  options.setWindowFn?.(this.moveTopK.bind(this));
139
20
  }
140
21
  createTopK(offset, limit, comparator) {
@@ -145,15 +26,10 @@ class TopKWithFractionalIndexOperator extends UnaryOperator {
145
26
  * Any changes to the topK are sent to the output.
146
27
  */
147
28
  moveTopK({ offset, limit }) {
148
- if (!(this.#topK instanceof TopKArray)) {
149
- throw new Error(
150
- `Cannot move B+-tree implementation of TopK with fractional index`
151
- );
152
- }
153
29
  const result = [];
154
- const diff = this.#topK.move({ offset, limit });
155
- diff.moveIns.forEach((moveIn) => this.handleMoveIn(moveIn, result));
156
- diff.moveOuts.forEach((moveOut) => this.handleMoveOut(moveOut, result));
30
+ const diff = this.#state.move({ offset, limit });
31
+ diff.moveIns.forEach((moveIn) => handleMoveIn(moveIn, result));
32
+ diff.moveOuts.forEach((moveOut) => handleMoveOut(moveOut, result));
157
33
  if (diff.changes) {
158
34
  this.output.sendData(new MultiSet(result));
159
35
  }
@@ -171,52 +47,9 @@ class TopKWithFractionalIndexOperator extends UnaryOperator {
171
47
  }
172
48
  }
173
49
  processElement(key, value, multiplicity, result) {
174
- const { oldMultiplicity, newMultiplicity } = this.addKey(key, multiplicity);
175
- let res = {
176
- moveIn: null,
177
- moveOut: null
178
- };
179
- if (oldMultiplicity <= 0 && newMultiplicity > 0) {
180
- const taggedValue = tagValue(key, value);
181
- res = this.#topK.insert(taggedValue);
182
- } else if (oldMultiplicity > 0 && newMultiplicity <= 0) {
183
- const taggedValue = tagValue(key, value);
184
- res = this.#topK.delete(taggedValue);
185
- } else ;
186
- this.handleMoveIn(res.moveIn, result);
187
- this.handleMoveOut(res.moveOut, result);
188
- return;
189
- }
190
- handleMoveIn(moveIn, result) {
191
- if (moveIn) {
192
- const index = getIndex(moveIn);
193
- const taggedValue = getValue(moveIn);
194
- const k = getKey(taggedValue);
195
- const val = getVal(taggedValue);
196
- result.push([[k, [val, index]], 1]);
197
- }
198
- }
199
- handleMoveOut(moveOut, result) {
200
- if (moveOut) {
201
- const index = getIndex(moveOut);
202
- const taggedValue = getValue(moveOut);
203
- const k = getKey(taggedValue);
204
- const val = getVal(taggedValue);
205
- result.push([[k, [val, index]], -1]);
206
- }
207
- }
208
- getMultiplicity(key) {
209
- return this.#index.get(key) ?? 0;
210
- }
211
- addKey(key, multiplicity) {
212
- const oldMultiplicity = this.getMultiplicity(key);
213
- const newMultiplicity = oldMultiplicity + multiplicity;
214
- if (newMultiplicity === 0) {
215
- this.#index.delete(key);
216
- } else {
217
- this.#index.set(key, newMultiplicity);
218
- }
219
- return { oldMultiplicity, newMultiplicity };
50
+ const changes = this.#state.processElement(key, value, multiplicity);
51
+ handleMoveIn(changes.moveIn, result);
52
+ handleMoveOut(changes.moveOut, result);
220
53
  }
221
54
  }
222
55
  function topKWithFractionalIndex(comparator, options) {
@@ -237,32 +70,8 @@ function topKWithFractionalIndex(comparator, options) {
237
70
  return output;
238
71
  };
239
72
  }
240
- function indexedValue(value, index) {
241
- return [value, index];
242
- }
243
- function getValue(indexedVal) {
244
- return indexedVal[0];
245
- }
246
- function getIndex(indexedVal) {
247
- return indexedVal[1];
248
- }
249
- function tagValue(key, value) {
250
- return [key, value, globalObjectIdGenerator.getId(key)];
251
- }
252
- function getKey(tieBreakerTaggedValue) {
253
- return tieBreakerTaggedValue[0];
254
- }
255
- function getVal(tieBreakerTaggedValue) {
256
- return tieBreakerTaggedValue[1];
257
- }
258
- function getTag(tieBreakerTaggedValue) {
259
- return tieBreakerTaggedValue[2];
260
- }
261
73
  export {
262
74
  TopKWithFractionalIndexOperator,
263
- getIndex,
264
- getValue,
265
- indexedValue,
266
75
  topKWithFractionalIndex
267
76
  };
268
77
  //# sourceMappingURL=topKWithFractionalIndex.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"topKWithFractionalIndex.js","sources":["../../../src/operators/topKWithFractionalIndex.ts"],"sourcesContent":["import { generateKeyBetween } from \"fractional-indexing\"\nimport { DifferenceStreamWriter, UnaryOperator } from \"../graph.js\"\nimport { StreamBuilder } from \"../d2.js\"\nimport { MultiSet } from \"../multiset.js\"\nimport {\n binarySearch,\n diffHalfOpen,\n globalObjectIdGenerator,\n} from \"../utils.js\"\nimport type { HRange } from \"../utils.js\"\nimport type { DifferenceStreamReader } from \"../graph.js\"\nimport type { IStreamBuilder, PipedOperator } from \"../types.js\"\n\nexport interface TopKWithFractionalIndexOptions {\n limit?: number\n offset?: number\n setSizeCallback?: (getSize: () => number) => void\n setWindowFn?: (\n windowFn: (options: { offset?: number; limit?: number }) => void\n ) => void\n}\n\nexport type TopKChanges<V> = {\n /** Indicates which element moves into the topK (if any) */\n moveIn: IndexedValue<V> | null\n /** Indicates which element moves out of the topK (if any) */\n moveOut: IndexedValue<V> | null\n}\n\nexport type TopKMoveChanges<V> = {\n /** Flag that marks whether there were any changes to the topK */\n changes: boolean\n /** Indicates which elements move into the topK (if any) */\n moveIns: Array<IndexedValue<V>>\n /** Indicates which elements move out of the topK (if any) */\n moveOuts: Array<IndexedValue<V>>\n}\n\n/**\n * A topK data structure that supports insertions and deletions\n * and returns changes to the topK.\n */\nexport interface TopK<V> {\n size: number\n insert: (value: V) => TopKChanges<V>\n delete: (value: V) => TopKChanges<V>\n}\n\n/**\n * Implementation of a topK data structure.\n * Uses a sorted array internally to store the values and keeps a topK window over that array.\n * Inserts and deletes are O(n) operations because worst case an element is inserted/deleted\n * at the start of the array which causes all the elements to shift to the right/left.\n */\nclass TopKArray<V> implements TopK<V> {\n #sortedValues: Array<IndexedValue<V>> = []\n #comparator: (a: V, b: V) => number\n #topKStart: number\n #topKEnd: number\n\n constructor(\n offset: number,\n limit: number,\n comparator: (a: V, b: V) => number\n ) {\n this.#topKStart = offset\n this.#topKEnd = offset + limit\n this.#comparator = comparator\n }\n\n get size(): number {\n const offset = this.#topKStart\n const limit = this.#topKEnd - this.#topKStart\n const available = this.#sortedValues.length - offset\n return Math.max(0, Math.min(limit, available))\n }\n\n /**\n * Moves the topK window\n */\n move({\n offset,\n limit,\n }: {\n offset?: number\n limit?: number\n }): TopKMoveChanges<V> {\n const oldOffset = this.#topKStart\n const oldLimit = this.#topKEnd - this.#topKStart\n\n // `this.#topKEnd` can be `Infinity` if it has no limit\n // but `diffHalfOpen` expects a finite range\n // so we restrict it to the size of the topK if topKEnd is infinite\n const oldRange: HRange = [\n this.#topKStart,\n this.#topKEnd === Infinity ? this.#topKStart + this.size : this.#topKEnd,\n ]\n\n this.#topKStart = offset ?? oldOffset\n this.#topKEnd = this.#topKStart + (limit ?? oldLimit) // can be `Infinity` if limit is `Infinity`\n\n // Also handle `Infinity` in the newRange\n const newRange: HRange = [\n this.#topKStart,\n this.#topKEnd === Infinity\n ? 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)\n : this.#topKEnd,\n ]\n const { onlyInA, onlyInB } = diffHalfOpen(oldRange, newRange)\n\n const moveIns: Array<IndexedValue<V>> = []\n onlyInB.forEach((index) => {\n const value = this.#sortedValues[index]\n if (value) {\n moveIns.push(value)\n }\n })\n\n const moveOuts: Array<IndexedValue<V>> = []\n onlyInA.forEach((index) => {\n const value = this.#sortedValues[index]\n if (value) {\n moveOuts.push(value)\n }\n })\n\n // It could be that there are changes (i.e. moveIns or moveOuts)\n // but that the collection is lazy so we don't have the data yet that needs to move in/out\n // so `moveIns` and `moveOuts` will be empty but `changes` will be true\n // this will tell the caller that it needs to run the graph to load more data\n return { moveIns, moveOuts, changes: onlyInA.length + onlyInB.length > 0 }\n }\n\n insert(value: V): TopKChanges<V> {\n const result: TopKChanges<V> = { moveIn: null, moveOut: null }\n\n // Lookup insert position\n const index = this.#findIndex(value)\n // Generate fractional index based on the fractional indices of the elements before and after it\n const indexBefore =\n index === 0 ? null : getIndex(this.#sortedValues[index - 1]!)\n const indexAfter =\n index === this.#sortedValues.length\n ? null\n : getIndex(this.#sortedValues[index]!)\n const fractionalIndex = generateKeyBetween(indexBefore, indexAfter)\n\n // Insert the value at the correct position\n const val = indexedValue(value, fractionalIndex)\n // Splice is O(n) where n = all elements in the collection (i.e. n >= k) !\n this.#sortedValues.splice(index, 0, val)\n\n // Check if the topK changed\n if (index < this.#topKEnd) {\n // The inserted element is either before the top K or within the top K\n // If it is before the top K then it moves the element that was right before the topK into the topK\n // If it is within the top K then the inserted element moves into the top K\n // In both cases the last element of the old top K now moves out of the top K\n const moveInIndex = Math.max(index, this.#topKStart)\n if (moveInIndex < this.#sortedValues.length) {\n // We actually have a topK\n // because in some cases there may not be enough elements in the array to reach the start of the topK\n // e.g. [1, 2, 3] with K = 2 and offset = 3 does not have a topK\n result.moveIn = this.#sortedValues[moveInIndex]!\n\n // We need to remove the element that falls out of the top K\n // The element that falls out of the top K has shifted one to the right\n // because of the element we inserted, so we find it at index topKEnd\n if (this.#topKEnd < this.#sortedValues.length) {\n result.moveOut = this.#sortedValues[this.#topKEnd]!\n }\n }\n }\n\n return result\n }\n\n /**\n * Deletes a value that may or may not be in the topK.\n * IMPORTANT: this assumes that the value is present in the collection\n * if it's not the case it will remove the element\n * that is on the position where the provided `value` would be.\n */\n delete(value: V): TopKChanges<V> {\n const result: TopKChanges<V> = { moveIn: null, moveOut: null }\n\n // Lookup delete position\n const index = this.#findIndex(value)\n // Remove the value at that position\n const [removedElem] = this.#sortedValues.splice(index, 1)\n\n // Check if the topK changed\n if (index < this.#topKEnd) {\n // The removed element is either before the top K or within the top K\n // If it is before the top K then the first element of the topK moves out of the topK\n // If it is within the top K then the removed element moves out of the topK\n result.moveOut = removedElem!\n if (index < this.#topKStart) {\n // The removed element is before the topK\n // so actually, the first element of the topK moves out of the topK\n // and not the element that we removed\n // The first element of the topK is now at index topKStart - 1\n // since we removed an element before the topK\n const moveOutIndex = this.#topKStart - 1\n if (moveOutIndex < this.#sortedValues.length) {\n result.moveOut = this.#sortedValues[moveOutIndex]!\n } else {\n // No value is moving out of the topK\n // because there are no elements in the topK\n result.moveOut = null\n }\n }\n\n // Since we removed an element that was before or in the topK\n // the first element after the topK moved one position to the left\n // and thus falls into the topK now\n const moveInIndex = this.#topKEnd - 1\n if (moveInIndex < this.#sortedValues.length) {\n result.moveIn = this.#sortedValues[moveInIndex]!\n }\n }\n\n return result\n }\n\n // TODO: see if there is a way to refactor the code for insert and delete in the topK above\n // because they are very similar, one is shifting the topK window to the left and the other is shifting it to the right\n // so i have the feeling there is a common pattern here and we can implement both cases using that pattern\n\n #findIndex(value: V): number {\n return binarySearch(this.#sortedValues, indexedValue(value, ``), (a, b) =>\n this.#comparator(getValue(a), getValue(b))\n )\n }\n}\n\n/**\n * Operator for fractional indexed topK operations\n * This operator maintains fractional indices for sorted elements\n * and only updates indices when elements move position\n */\nexport class TopKWithFractionalIndexOperator<K, T> extends UnaryOperator<\n [K, T],\n [K, IndexedValue<T>]\n> {\n #index: Map<K, number> = new Map() // maps keys to their multiplicity\n\n /**\n * topK data structure that supports insertions and deletions\n * and returns changes to the topK.\n */\n #topK: TopK<TaggedValue<K, T>>\n\n constructor(\n id: number,\n inputA: DifferenceStreamReader<[K, T]>,\n output: DifferenceStreamWriter<[K, IndexedValue<T>]>,\n comparator: (a: T, b: T) => number,\n options: TopKWithFractionalIndexOptions\n ) {\n super(id, inputA, output)\n const limit = options.limit ?? Infinity\n const offset = options.offset ?? 0\n const compareTaggedValues = (\n a: TaggedValue<K, T>,\n b: TaggedValue<K, T>\n ) => {\n // First compare on the value\n const valueComparison = comparator(getVal(a), getVal(b))\n if (valueComparison !== 0) {\n return valueComparison\n }\n // If the values are equal, compare on the tag (object identity)\n const tieBreakerA = getTag(a)\n const tieBreakerB = getTag(b)\n return tieBreakerA - tieBreakerB\n }\n this.#topK = this.createTopK(offset, limit, compareTaggedValues)\n options.setSizeCallback?.(() => this.#topK.size)\n options.setWindowFn?.(this.moveTopK.bind(this))\n }\n\n protected createTopK(\n offset: number,\n limit: number,\n comparator: (a: TaggedValue<K, T>, b: TaggedValue<K, T>) => number\n ): TopK<TaggedValue<K, T>> {\n return new TopKArray(offset, limit, comparator)\n }\n\n /**\n * Moves the topK window based on the provided offset and limit.\n * Any changes to the topK are sent to the output.\n */\n moveTopK({ offset, limit }: { offset?: number; limit?: number }) {\n if (!(this.#topK instanceof TopKArray)) {\n throw new Error(\n `Cannot move B+-tree implementation of TopK with fractional index`\n )\n }\n\n const result: Array<[[K, IndexedValue<T>], number]> = []\n\n const diff = this.#topK.move({ offset, limit })\n\n diff.moveIns.forEach((moveIn) => this.handleMoveIn(moveIn, result))\n diff.moveOuts.forEach((moveOut) => this.handleMoveOut(moveOut, result))\n\n if (diff.changes) {\n // There are changes to the topK\n // it could be that moveIns and moveOuts are empty\n // because the collection is lazy, so we will run the graph again to load the data\n this.output.sendData(new MultiSet(result))\n }\n }\n\n run(): void {\n const result: Array<[[K, IndexedValue<T>], number]> = []\n for (const message of this.inputMessages()) {\n for (const [item, multiplicity] of message.getInner()) {\n const [key, value] = item\n this.processElement(key, value, multiplicity, result)\n }\n }\n\n if (result.length > 0) {\n this.output.sendData(new MultiSet(result))\n }\n }\n\n processElement(\n key: K,\n value: T,\n multiplicity: number,\n result: Array<[[K, IndexedValue<T>], number]>\n ): void {\n const { oldMultiplicity, newMultiplicity } = this.addKey(key, multiplicity)\n\n let res: TopKChanges<TaggedValue<K, T>> = {\n moveIn: null,\n moveOut: null,\n }\n if (oldMultiplicity <= 0 && newMultiplicity > 0) {\n // The value was invisible but should now be visible\n // Need to insert it into the array of sorted values\n const taggedValue = tagValue(key, value)\n res = this.#topK.insert(taggedValue)\n } else if (oldMultiplicity > 0 && newMultiplicity <= 0) {\n // The value was visible but should now be invisible\n // Need to remove it from the array of sorted values\n const taggedValue = tagValue(key, value)\n res = this.#topK.delete(taggedValue)\n } else {\n // The value was invisible and it remains invisible\n // or it was visible and remains visible\n // so it doesn't affect the topK\n }\n\n this.handleMoveIn(res.moveIn, result)\n this.handleMoveOut(res.moveOut, result)\n\n return\n }\n\n private handleMoveIn(\n moveIn: IndexedValue<TaggedValue<K, T>> | null,\n result: Array<[[K, IndexedValue<T>], number]>\n ) {\n if (moveIn) {\n const index = getIndex(moveIn)\n const taggedValue = getValue(moveIn)\n const k = getKey(taggedValue)\n const val = getVal(taggedValue)\n result.push([[k, [val, index]], 1])\n }\n }\n\n private handleMoveOut(\n moveOut: IndexedValue<TaggedValue<K, T>> | null,\n result: Array<[[K, IndexedValue<T>], number]>\n ) {\n if (moveOut) {\n const index = getIndex(moveOut)\n const taggedValue = getValue(moveOut)\n const k = getKey(taggedValue)\n const val = getVal(taggedValue)\n result.push([[k, [val, index]], -1])\n }\n }\n\n private getMultiplicity(key: K): number {\n return this.#index.get(key) ?? 0\n }\n\n private addKey(\n key: K,\n multiplicity: number\n ): { oldMultiplicity: number; newMultiplicity: number } {\n const oldMultiplicity = this.getMultiplicity(key)\n const newMultiplicity = oldMultiplicity + multiplicity\n if (newMultiplicity === 0) {\n this.#index.delete(key)\n } else {\n this.#index.set(key, newMultiplicity)\n }\n return { oldMultiplicity, newMultiplicity }\n }\n}\n\n/**\n * Limits the number of results based on a comparator, with optional offset.\n * Uses fractional indexing to minimize the number of changes when elements move positions.\n * Each element is assigned a fractional index that is lexicographically sortable.\n * When elements move, only the indices of the moved elements are updated, not all elements.\n *\n * @param comparator - A function that compares two elements\n * @param options - An optional object containing limit and offset properties\n * @returns A piped operator that orders the elements and limits the number of results\n */\nexport function topKWithFractionalIndex<KType, T>(\n comparator: (a: T, b: T) => number,\n options?: TopKWithFractionalIndexOptions\n): PipedOperator<[KType, T], [KType, IndexedValue<T>]> {\n const opts = options || {}\n\n return (\n stream: IStreamBuilder<[KType, T]>\n ): IStreamBuilder<[KType, IndexedValue<T>]> => {\n const output = new StreamBuilder<[KType, IndexedValue<T>]>(\n stream.graph,\n new DifferenceStreamWriter<[KType, IndexedValue<T>]>()\n )\n const operator = new TopKWithFractionalIndexOperator<KType, T>(\n stream.graph.getNextOperatorId(),\n stream.connectReader(),\n output.writer,\n comparator,\n opts\n )\n stream.graph.addOperator(operator)\n return output\n }\n}\n\n// Abstraction for fractionally indexed values\nexport type FractionalIndex = string\nexport type IndexedValue<V> = [V, FractionalIndex]\n\nexport function indexedValue<V>(\n value: V,\n index: FractionalIndex\n): IndexedValue<V> {\n return [value, index]\n}\n\nexport function getValue<V>(indexedVal: IndexedValue<V>): V {\n return indexedVal[0]\n}\n\nexport function getIndex<V>(indexedVal: IndexedValue<V>): FractionalIndex {\n return indexedVal[1]\n}\n\nexport type Tag = number\nexport type TaggedValue<K, V> = [K, V, Tag]\n\nfunction tagValue<K, V>(key: K, value: V): TaggedValue<K, V> {\n return [key, value, globalObjectIdGenerator.getId(key)]\n}\n\nfunction getKey<K, V>(tieBreakerTaggedValue: TaggedValue<K, V>): K {\n return tieBreakerTaggedValue[0]\n}\n\nfunction getVal<K, V>(tieBreakerTaggedValue: TaggedValue<K, V>): V {\n return tieBreakerTaggedValue[1]\n}\n\nfunction getTag<K, V>(tieBreakerTaggedValue: TaggedValue<K, V>): Tag {\n return tieBreakerTaggedValue[2]\n}\n"],"names":[],"mappings":";;;;;AAsDA,MAAM,UAAgC;AAAA,EACpC,gBAAwC,CAAA;AAAA,EACxC;AAAA,EACA;AAAA,EACA;AAAA,EAEA,YACE,QACA,OACA,YACA;AACA,SAAK,aAAa;AAClB,SAAK,WAAW,SAAS;AACzB,SAAK,cAAc;AAAA,EACrB;AAAA,EAEA,IAAI,OAAe;AACjB,UAAM,SAAS,KAAK;AACpB,UAAM,QAAQ,KAAK,WAAW,KAAK;AACnC,UAAM,YAAY,KAAK,cAAc,SAAS;AAC9C,WAAO,KAAK,IAAI,GAAG,KAAK,IAAI,OAAO,SAAS,CAAC;AAAA,EAC/C;AAAA;AAAA;AAAA;AAAA,EAKA,KAAK;AAAA,IACH;AAAA,IACA;AAAA,EAAA,GAIqB;AACrB,UAAM,YAAY,KAAK;AACvB,UAAM,WAAW,KAAK,WAAW,KAAK;AAKtC,UAAM,WAAmB;AAAA,MACvB,KAAK;AAAA,MACL,KAAK,aAAa,WAAW,KAAK,aAAa,KAAK,OAAO,KAAK;AAAA,IAAA;AAGlE,SAAK,aAAa,UAAU;AAC5B,SAAK,WAAW,KAAK,cAAc,SAAS;AAG5C,UAAM,WAAmB;AAAA,MACvB,KAAK;AAAA,MACL,KAAK,aAAa,WACd,KAAK,IAAI,KAAK,aAAa,KAAK,MAAM,SAAS,CAAC,CAAC,IACjD,KAAK;AAAA,IAAA;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O,SAAS,wBACd,YACA,SACqD;AACrD,QAAM,OAAO,WAAW,CAAA;AAExB,SAAO,CACL,WAC6C;AAC7C,UAAM,SAAS,IAAI;AAAA,MACjB,OAAO;AAAA,MACP,IAAI,uBAAA;AAAA,IAAiD;AAEvD,UAAM,WAAW,IAAI;AAAA,MACnB,OAAO,MAAM,kBAAA;AAAA,MACb,OAAO,cAAA;AAAA,MACP,OAAO;AAAA,MACP;AAAA,MACA;AAAA,IAAA;AAEF,WAAO,MAAM,YAAY,QAAQ;AACjC,WAAO;AAAA,EACT;AACF;AAMO,SAAS,aACd,OACA,OACiB;AACjB,SAAO,CAAC,OAAO,KAAK;AACtB;AAEO,SAAS,SAAY,YAAgC;AAC1D,SAAO,WAAW,CAAC;AACrB;AAEO,SAAS,SAAY,YAA8C;AACxE,SAAO,WAAW,CAAC;AACrB;AAKA,SAAS,SAAe,KAAQ,OAA6B;AAC3D,SAAO,CAAC,KAAK,OAAO,wBAAwB,MAAM,GAAG,CAAC;AACxD;AAEA,SAAS,OAAa,uBAA6C;AACjE,SAAO,sBAAsB,CAAC;AAChC;AAEA,SAAS,OAAa,uBAA6C;AACjE,SAAO,sBAAsB,CAAC;AAChC;AAEA,SAAS,OAAa,uBAA+C;AACnE,SAAO,sBAAsB,CAAC;AAChC;"}
1
+ {"version":3,"file":"topKWithFractionalIndex.js","sources":["../../../src/operators/topKWithFractionalIndex.ts"],"sourcesContent":["import { DifferenceStreamWriter, UnaryOperator } from '../graph.js'\nimport { StreamBuilder } from '../d2.js'\nimport { MultiSet } from '../multiset.js'\nimport { TopKState, handleMoveIn, handleMoveOut } from './topKState.js'\nimport { TopKArray, createKeyedComparator } from './topKArray.js'\nimport type { IndexedValue, TopK } from './topKArray.js'\nimport type { DifferenceStreamReader } from '../graph.js'\nimport type { IStreamBuilder, PipedOperator } from '../types.js'\n\nexport interface TopKWithFractionalIndexOptions {\n limit?: number\n offset?: number\n setSizeCallback?: (getSize: () => number) => void\n setWindowFn?: (\n windowFn: (options: { offset?: number; limit?: number }) => void,\n ) => void\n}\n\n/**\n * Operator for fractional indexed topK operations\n * This operator maintains fractional indices for sorted elements\n * and only updates indices when elements move position\n */\nexport class TopKWithFractionalIndexOperator<\n K extends string | number,\n T,\n> extends UnaryOperator<[K, T], [K, IndexedValue<T>]> {\n #state: TopKState<K, T>\n\n constructor(\n id: number,\n inputA: DifferenceStreamReader<[K, T]>,\n output: DifferenceStreamWriter<[K, IndexedValue<T>]>,\n comparator: (a: T, b: T) => number,\n options: TopKWithFractionalIndexOptions,\n ) {\n super(id, inputA, output)\n const limit = options.limit ?? Infinity\n const offset = options.offset ?? 0\n const topK = this.createTopK(\n offset,\n limit,\n createKeyedComparator(comparator),\n )\n this.#state = new TopKState(topK)\n options.setSizeCallback?.(() => this.#state.size)\n options.setWindowFn?.(this.moveTopK.bind(this))\n }\n\n protected createTopK(\n offset: number,\n limit: number,\n comparator: (a: [K, T], b: [K, T]) => number,\n ): TopK<[K, T]> {\n return new TopKArray(offset, limit, comparator)\n }\n\n /**\n * Moves the topK window based on the provided offset and limit.\n * Any changes to the topK are sent to the output.\n */\n moveTopK({ offset, limit }: { offset?: number; limit?: number }) {\n const result: Array<[[K, IndexedValue<T>], number]> = []\n const diff = this.#state.move({ offset, limit })\n\n diff.moveIns.forEach((moveIn) => handleMoveIn(moveIn, result))\n diff.moveOuts.forEach((moveOut) => handleMoveOut(moveOut, result))\n\n if (diff.changes) {\n // There are changes to the topK\n // it could be that moveIns and moveOuts are empty\n // because the collection is lazy, so we will run the graph again to load the data\n this.output.sendData(new MultiSet(result))\n }\n }\n\n run(): void {\n const result: Array<[[K, IndexedValue<T>], number]> = []\n for (const message of this.inputMessages()) {\n for (const [item, multiplicity] of message.getInner()) {\n const [key, value] = item\n this.processElement(key, value, multiplicity, result)\n }\n }\n\n if (result.length > 0) {\n this.output.sendData(new MultiSet(result))\n }\n }\n\n processElement(\n key: K,\n value: T,\n multiplicity: number,\n result: Array<[[K, IndexedValue<T>], number]>,\n ): void {\n const changes = this.#state.processElement(key, value, multiplicity)\n handleMoveIn(changes.moveIn, result)\n handleMoveOut(changes.moveOut, result)\n }\n}\n\n/**\n * Limits the number of results based on a comparator, with optional offset.\n * Uses fractional indexing to minimize the number of changes when elements move positions.\n * Each element is assigned a fractional index that is lexicographically sortable.\n * When elements move, only the indices of the moved elements are updated, not all elements.\n *\n * @param comparator - A function that compares two elements\n * @param options - An optional object containing limit and offset properties\n * @returns A piped operator that orders the elements and limits the number of results\n */\nexport function topKWithFractionalIndex<KType extends string | number, T>(\n comparator: (a: T, b: T) => number,\n options?: TopKWithFractionalIndexOptions,\n): PipedOperator<[KType, T], [KType, IndexedValue<T>]> {\n const opts = options || {}\n\n return (\n stream: IStreamBuilder<[KType, T]>,\n ): IStreamBuilder<[KType, IndexedValue<T>]> => {\n const output = new StreamBuilder<[KType, IndexedValue<T>]>(\n stream.graph,\n new DifferenceStreamWriter<[KType, IndexedValue<T>]>(),\n )\n const operator = new TopKWithFractionalIndexOperator<KType, T>(\n stream.graph.getNextOperatorId(),\n stream.connectReader(),\n output.writer,\n comparator,\n opts,\n )\n stream.graph.addOperator(operator)\n return output\n }\n}\n"],"names":[],"mappings":";;;;;AAuBO,MAAM,wCAGH,cAA4C;AAAA,EACpD;AAAA,EAEA,YACE,IACA,QACA,QACA,YACA,SACA;AACA,UAAM,IAAI,QAAQ,MAAM;AACxB,UAAM,QAAQ,QAAQ,SAAS;AAC/B,UAAM,SAAS,QAAQ,UAAU;AACjC,UAAM,OAAO,KAAK;AAAA,MAChB;AAAA,MACA;AAAA,MACA,sBAAsB,UAAU;AAAA,IAAA;AAElC,SAAK,SAAS,IAAI,UAAU,IAAI;AAChC,YAAQ,kBAAkB,MAAM,KAAK,OAAO,IAAI;AAChD,YAAQ,cAAc,KAAK,SAAS,KAAK,IAAI,CAAC;AAAA,EAChD;AAAA,EAEU,WACR,QACA,OACA,YACc;AACd,WAAO,IAAI,UAAU,QAAQ,OAAO,UAAU;AAAA,EAChD;AAAA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 +1,5 @@
1
- import { TopKWithFractionalIndexOperator, IndexedValue, TaggedValue, TopK, TopKWithFractionalIndexOptions } from './topKWithFractionalIndex.js';
1
+ import { TopKWithFractionalIndexOperator, TopKWithFractionalIndexOptions } from './topKWithFractionalIndex.js';
2
+ import { IndexedValue, TopK } from './topKArray.js';
2
3
  import { PipedOperator } from '../types.js';
3
4
  export declare function loadBTree(): Promise<void>;
4
5
  /**
@@ -6,8 +7,8 @@ export declare function loadBTree(): Promise<void>;
6
7
  * This operator maintains fractional indices for sorted elements
7
8
  * and only updates indices when elements move position
8
9
  */
9
- export declare class TopKWithFractionalIndexBTreeOperator<K, T> extends TopKWithFractionalIndexOperator<K, T> {
10
- protected createTopK(offset: number, limit: number, comparator: (a: TaggedValue<K, T>, b: TaggedValue<K, T>) => number): TopK<TaggedValue<K, T>>;
10
+ export declare class TopKWithFractionalIndexBTreeOperator<K extends string | number, T> extends TopKWithFractionalIndexOperator<K, T> {
11
+ protected createTopK(offset: number, limit: number, comparator: (a: [K, T], b: [K, T]) => number): TopK<[K, T]>;
11
12
  }
12
13
  /**
13
14
  * Limits the number of results based on a comparator, with optional offset.
@@ -24,4 +25,4 @@ export declare class TopKWithFractionalIndexBTreeOperator<K, T> extends TopKWith
24
25
  * @param options - An optional object containing limit and offset properties
25
26
  * @returns A piped operator that orders the elements and limits the number of results
26
27
  */
27
- export declare function topKWithFractionalIndexBTree<KType, T>(comparator: (a: T, b: T) => number, options?: TopKWithFractionalIndexOptions): PipedOperator<[KType, T], [KType, IndexedValue<T>]>;
28
+ export declare function topKWithFractionalIndexBTree<KType extends string | number, T>(comparator: (a: T, b: T) => number, options?: TopKWithFractionalIndexOptions): PipedOperator<[KType, T], [KType, IndexedValue<T>]>;
@@ -52,3 +52,14 @@ export declare function diffHalfOpen(a: HRange, b: HRange): {
52
52
  onlyInA: number[];
53
53
  onlyInB: number[];
54
54
  };
55
+ /**
56
+ * Compares two keys (string | number) in a consistent, deterministic way.
57
+ * Handles mixed types by ordering strings before numbers.
58
+ */
59
+ export declare function compareKeys(a: string | number, b: string | number): number;
60
+ /**
61
+ * Serializes a value for use as a key, handling BigInt and Date values that JSON.stringify cannot handle.
62
+ * Uses JSON.stringify with a replacer function to convert BigInt values to strings and Date values to ISO strings.
63
+ * This is used for creating string keys in groupBy operations.
64
+ */
65
+ export declare function serializeValue(value: unknown): string;
package/dist/esm/utils.js CHANGED
@@ -103,12 +103,33 @@ function range(start, end) {
103
103
  for (let i = start; i < end; i++) out.push(i);
104
104
  return out;
105
105
  }
106
+ function compareKeys(a, b) {
107
+ if (typeof a === typeof b) {
108
+ if (a < b) return -1;
109
+ if (a > b) return 1;
110
+ return 0;
111
+ }
112
+ return typeof a === `string` ? -1 : 1;
113
+ }
114
+ function serializeValue(value) {
115
+ return JSON.stringify(value, (_, val) => {
116
+ if (typeof val === "bigint") {
117
+ return val.toString();
118
+ }
119
+ if (val instanceof Date) {
120
+ return val.toISOString();
121
+ }
122
+ return val;
123
+ });
124
+ }
106
125
  export {
107
126
  DefaultMap,
108
127
  ObjectIdGenerator,
109
128
  binarySearch,
110
129
  chunkedArrayPush,
130
+ compareKeys,
111
131
  diffHalfOpen,
112
- globalObjectIdGenerator
132
+ globalObjectIdGenerator,
133
+ serializeValue
113
134
  };
114
135
  //# sourceMappingURL=utils.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sources":["../../src/utils.ts"],"sourcesContent":["/**\n * Simple assertion function for runtime checks.\n * Throws an error if the condition is false.\n */\nexport function assert(\n condition: unknown,\n message?: string\n): asserts condition {\n if (!condition) {\n throw new Error(message || `Assertion failed`)\n }\n}\n\n/**\n * A map that returns a default value for keys that are not present.\n */\nexport class DefaultMap<K, V> extends Map<K, V> {\n constructor(\n private defaultValue: () => V,\n entries?: Iterable<[K, V]>\n ) {\n super(entries)\n }\n\n get(key: K): V {\n if (!this.has(key)) {\n // this.set(key, this.defaultValue())\n return this.defaultValue()\n }\n return super.get(key)!\n }\n\n /**\n * Update the value for a key using a function.\n */\n update(key: K, updater: (value: V) => V): V {\n const value = this.get(key)\n const newValue = updater(value)\n this.set(key, newValue)\n return newValue\n }\n}\n\n// JS engines have various limits on how many args can be passed to a function\n// with a spread operator, so we need to split the operation into chunks\n// 32767 is the max for Chrome 14, all others are higher\n// TODO: investigate the performance of this and other approaches\nconst chunkSize = 30000\nexport function chunkedArrayPush(array: Array<unknown>, other: Array<unknown>) {\n if (other.length <= chunkSize) {\n array.push(...other)\n } else {\n for (let i = 0; i < other.length; i += chunkSize) {\n const chunk = other.slice(i, i + chunkSize)\n array.push(...chunk)\n }\n }\n}\n\nexport function binarySearch<T>(\n array: Array<T>,\n value: T,\n comparator: (a: T, b: T) => number\n): number {\n let low = 0\n let high = array.length\n while (low < high) {\n const mid = Math.floor((low + high) / 2)\n const comparison = comparator(array[mid]!, value)\n if (comparison < 0) {\n low = mid + 1\n } else if (comparison > 0) {\n high = mid\n } else {\n return mid\n }\n }\n return low\n}\n\n/**\n * Utility for generating unique IDs for objects and values.\n * Uses WeakMap for object reference tracking and consistent hashing for primitives.\n */\nexport class ObjectIdGenerator {\n private objectIds = new WeakMap<object, number>()\n private nextId = 0\n\n /**\n * Get a unique identifier for any value.\n * - Objects: Uses WeakMap for reference-based identity\n * - Primitives: Uses consistent string-based hashing\n */\n getId(value: any): number {\n // For primitives, use a simple hash of their string representation\n if (typeof value !== `object` || value === null) {\n const str = String(value)\n let hashValue = 0\n for (let i = 0; i < str.length; i++) {\n const char = str.charCodeAt(i)\n hashValue = (hashValue << 5) - hashValue + char\n hashValue = hashValue & hashValue // Convert to 32-bit integer\n }\n return hashValue\n }\n\n // For objects, use WeakMap to assign unique IDs\n if (!this.objectIds.has(value)) {\n this.objectIds.set(value, this.nextId++)\n }\n return this.objectIds.get(value)!\n }\n\n /**\n * Get a string representation of the ID for use in composite keys.\n */\n getStringId(value: any): string {\n if (value === null) return `null`\n if (value === undefined) return `undefined`\n if (typeof value !== `object`) return `str_${String(value)}`\n\n return `obj_${this.getId(value)}`\n }\n}\n\n/**\n * Global instance for cases where a shared object ID space is needed.\n */\nexport const globalObjectIdGenerator = new ObjectIdGenerator()\n\nexport function* concatIterable<T>(\n ...iterables: Array<Iterable<T>>\n): Iterable<T> {\n for (const iterable of iterables) {\n yield* iterable\n }\n}\n\nexport function* mapIterable<T, U>(\n it: Iterable<T>,\n fn: (t: T) => U\n): Iterable<U> {\n for (const t of it) {\n yield fn(t)\n }\n}\n\nexport type HRange = [number, number] // half-open [start, end[ i.e. end is exclusive\n\n/**\n * Computes the difference between two half-open ranges.\n * @param a - The first half-open range\n * @param b - The second half-open range\n * @returns The difference between the two ranges\n */\nexport function diffHalfOpen(a: HRange, b: HRange) {\n const [a1, a2] = a\n const [b1, b2] = b\n\n // A \\ B can be up to two segments (left and right of the overlap)\n const onlyInA: Array<number> = [\n ...range(a1, Math.min(a2, b1)), // left side of A outside B\n ...range(Math.max(a1, b2), a2), // right side of A outside B\n ]\n\n // B \\ A similarly\n const onlyInB: Array<number> = [\n ...range(b1, Math.min(b2, a1)),\n ...range(Math.max(b1, a2), b2),\n ]\n\n return { onlyInA, onlyInB }\n}\n\nfunction range(start: number, end: number): Array<number> {\n const out: Array<number> = []\n for (let i = start; i < end; i++) out.push(i)\n return out\n}\n"],"names":[],"mappings":"AAgBO,MAAM,mBAAyB,IAAU;AAAA,EAC9C,YACU,cACR,SACA;AACA,UAAM,OAAO;AAHL,SAAA,eAAA;AAAA,EAIV;AAAA,EAEA,IAAI,KAAW;AACb,QAAI,CAAC,KAAK,IAAI,GAAG,GAAG;AAElB,aAAO,KAAK,aAAA;AAAA,IACd;AACA,WAAO,MAAM,IAAI,GAAG;AAAA,EACtB;AAAA;AAAA;AAAA;AAAA,EAKA,OAAO,KAAQ,SAA6B;AAC1C,UAAM,QAAQ,KAAK,IAAI,GAAG;AAC1B,UAAM,WAAW,QAAQ,KAAK;AAC9B,SAAK,IAAI,KAAK,QAAQ;AACtB,WAAO;AAAA,EACT;AACF;AAMA,MAAM,YAAY;A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AC9B,QAAI,UAAU,KAAM,QAAO;AAC3B,QAAI,UAAU,OAAW,QAAO;AAChC,QAAI,OAAO,UAAU,iBAAiB,OAAO,OAAO,KAAK,CAAC;AAE1D,WAAO,OAAO,KAAK,MAAM,KAAK,CAAC;AAAA,EACjC;AACF;AAKO,MAAM,0BAA0B,IAAI,kBAAA;AA2BpC,SAAS,aAAa,GAAW,GAAW;AACjD,QAAM,CAAC,IAAI,EAAE,IAAI;AACjB,QAAM,CAAC,IAAI,EAAE,IAAI;AAGjB,QAAM,UAAyB;AAAA,IAC7B,GAAG,MAAM,IAAI,KAAK,IAAI,IAAI,EAAE,CAAC;AAAA;AAAA,IAC7B,GAAG,MAAM,KAAK,IAAI,IAAI,EAAE,GAAG,EAAE;AAAA;AAAA,EAAA;AAI/B,QAAM,UAAyB;AAAA,IAC7B,GAAG,MAAM,IAAI,KAAK,IAAI,IAAI,EAAE,CAAC;AAAA,IAC7B,GAAG,MAAM,KAAK,IAAI,IAAI,EAAE,GAAG,EAAE;AAAA,EAAA;AAG/B,SAAO,EAAE,SAAS,QAAA;AACpB;AAEA,SAAS,MAAM,OAAe,KAA4B;AACxD,QAAM,MAAqB,CAAA;AAC3B,WAAS,IAAI,OAAO,IAAI,KAAK,IAAK,KAAI,KAAK,CAAC;AAC5C,SAAO;AACT;"}
1
+ {"version":3,"file":"utils.js","sources":["../../src/utils.ts"],"sourcesContent":["/**\n * Simple assertion function for runtime checks.\n * Throws an error if the condition is false.\n */\nexport function assert(\n condition: unknown,\n message?: string,\n): asserts condition {\n if (!condition) {\n throw new Error(message || `Assertion failed`)\n }\n}\n\n/**\n * A map that returns a default value for keys that are not present.\n */\nexport class DefaultMap<K, V> extends Map<K, V> {\n constructor(\n private defaultValue: () => V,\n entries?: Iterable<[K, V]>,\n ) {\n super(entries)\n }\n\n get(key: K): V {\n if (!this.has(key)) {\n // this.set(key, this.defaultValue())\n return this.defaultValue()\n }\n return super.get(key)!\n }\n\n /**\n * Update the value for a key using a function.\n */\n update(key: K, updater: (value: V) => V): V {\n const value = this.get(key)\n const newValue = updater(value)\n this.set(key, newValue)\n return newValue\n }\n}\n\n// JS engines have various limits on how many args can be passed to a function\n// with a spread operator, so we need to split the operation into chunks\n// 32767 is the max for Chrome 14, all others are higher\n// TODO: investigate the performance of this and other approaches\nconst chunkSize = 30000\nexport function chunkedArrayPush(array: Array<unknown>, other: Array<unknown>) {\n if (other.length <= chunkSize) {\n array.push(...other)\n } else {\n for (let i = 0; i < other.length; i += chunkSize) {\n const chunk = other.slice(i, i + chunkSize)\n array.push(...chunk)\n }\n }\n}\n\nexport function binarySearch<T>(\n array: Array<T>,\n value: T,\n comparator: (a: T, b: T) => number,\n): number {\n let low = 0\n let high = array.length\n while (low < high) {\n const mid = Math.floor((low + high) / 2)\n const comparison = comparator(array[mid]!, value)\n if (comparison < 0) {\n low = mid + 1\n } else if (comparison > 0) {\n high = mid\n } else {\n return mid\n }\n }\n return low\n}\n\n/**\n * Utility for generating unique IDs for objects and values.\n * Uses WeakMap for object reference tracking and consistent hashing for primitives.\n */\nexport class ObjectIdGenerator {\n private objectIds = new WeakMap<object, number>()\n private nextId = 0\n\n /**\n * Get a unique identifier for any value.\n * - Objects: Uses WeakMap for reference-based identity\n * - Primitives: Uses consistent string-based hashing\n */\n getId(value: any): number {\n // For primitives, use a simple hash of their string representation\n if (typeof value !== `object` || value === null) {\n const str = String(value)\n let hashValue = 0\n for (let i = 0; i < str.length; i++) {\n const char = str.charCodeAt(i)\n hashValue = (hashValue << 5) - hashValue + char\n hashValue = hashValue & hashValue // Convert to 32-bit integer\n }\n return hashValue\n }\n\n // For objects, use WeakMap to assign unique IDs\n if (!this.objectIds.has(value)) {\n this.objectIds.set(value, this.nextId++)\n }\n return this.objectIds.get(value)!\n }\n\n /**\n * Get a string representation of the ID for use in composite keys.\n */\n getStringId(value: any): string {\n if (value === null) return `null`\n if (value === undefined) return `undefined`\n if (typeof value !== `object`) return `str_${String(value)}`\n\n return `obj_${this.getId(value)}`\n }\n}\n\n/**\n * Global instance for cases where a shared object ID space is needed.\n */\nexport const globalObjectIdGenerator = new ObjectIdGenerator()\n\nexport function* concatIterable<T>(\n ...iterables: Array<Iterable<T>>\n): Iterable<T> {\n for (const iterable of iterables) {\n yield* iterable\n }\n}\n\nexport function* mapIterable<T, U>(\n it: Iterable<T>,\n fn: (t: T) => U,\n): Iterable<U> {\n for (const t of it) {\n yield fn(t)\n }\n}\n\nexport type HRange = [number, number] // half-open [start, end[ i.e. end is exclusive\n\n/**\n * Computes the difference between two half-open ranges.\n * @param a - The first half-open range\n * @param b - The second half-open range\n * @returns The difference between the two ranges\n */\nexport function diffHalfOpen(a: HRange, b: HRange) {\n const [a1, a2] = a\n const [b1, b2] = b\n\n // A \\ B can be up to two segments (left and right of the overlap)\n const onlyInA: Array<number> = [\n ...range(a1, Math.min(a2, b1)), // left side of A outside B\n ...range(Math.max(a1, b2), a2), // right side of A outside B\n ]\n\n // B \\ A similarly\n const onlyInB: Array<number> = [\n ...range(b1, Math.min(b2, a1)),\n ...range(Math.max(b1, a2), b2),\n ]\n\n return { onlyInA, onlyInB }\n}\n\nfunction range(start: number, end: number): Array<number> {\n const out: Array<number> = []\n for (let i = start; i < end; i++) out.push(i)\n return out\n}\n\n/**\n * Compares two keys (string | number) in a consistent, deterministic way.\n * Handles mixed types by ordering strings before numbers.\n */\nexport function compareKeys(a: string | number, b: string | number): number {\n // Same type: compare directly\n if (typeof a === typeof b) {\n if (a < b) return -1\n if (a > b) return 1\n return 0\n }\n // Different types: strings come before numbers\n return typeof a === `string` ? -1 : 1\n}\n\n/**\n * Serializes a value for use as a key, handling BigInt and Date values that JSON.stringify cannot handle.\n * Uses JSON.stringify with a replacer function to convert BigInt values to strings and Date values to ISO strings.\n * This is used for creating string keys in groupBy operations.\n */\nexport function serializeValue(value: unknown): string {\n return JSON.stringify(value, (_, val) => {\n if (typeof val === 'bigint') {\n return val.toString()\n }\n if (val instanceof Date) {\n return val.toISOString()\n }\n return val\n })\n}\n"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K,KAAI,KAAK,CAAC;AAC5C,SAAO;AACT;AAMO,SAAS,YAAY,GAAoB,GAA4B;AAE1E,MAAI,OAAO,MAAM,OAAO,GAAG;AACzB,QAAI,IAAI,EAAG,QAAO;AAClB,QAAI,IAAI,EAAG,QAAO;AAClB,WAAO;AAAA,EACT;AAEA,SAAO,OAAO,MAAM,WAAW,KAAK;AACtC;AAOO,SAAS,eAAe,OAAwB;AACrD,SAAO,KAAK,UAAU,OAAO,CAAC,GAAG,QAAQ;AACvC,QAAI,OAAO,QAAQ,UAAU;AAC3B,aAAO,IAAI,SAAA;AAAA,IACb;AACA,QAAI,eAAe,MAAM;AACvB,aAAO,IAAI,YAAA;AAAA,IACb;AACA,WAAO;AAAA,EACT,CAAC;AACH;"}
package/package.json CHANGED
@@ -1,15 +1,27 @@
1
1
  {
2
2
  "name": "@tanstack/db-ivm",
3
+ "version": "0.1.15",
3
4
  "description": "Incremental View Maintenance for TanStack DB based on Differential Dataflow",
4
- "version": "0.1.13",
5
- "dependencies": {
6
- "fractional-indexing": "^3.2.0",
7
- "sorted-btree": "^1.8.1"
8
- },
9
- "devDependencies": {
10
- "@types/debug": "^4.1.12",
11
- "@vitest/coverage-istanbul": "^3.2.4"
5
+ "author": "Sam Willis",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/TanStack/db.git",
10
+ "directory": "packages/db-ivm"
12
11
  },
12
+ "homepage": "https://tanstack.com/db",
13
+ "keywords": [
14
+ "electric",
15
+ "sql",
16
+ "optimistic",
17
+ "typescript",
18
+ "ivm",
19
+ "differential-dataflow"
20
+ ],
21
+ "type": "module",
22
+ "main": "dist/cjs/index.cjs",
23
+ "module": "dist/esm/index.js",
24
+ "types": "dist/esm/index.d.ts",
13
25
  "exports": {
14
26
  ".": {
15
27
  "import": {
@@ -23,38 +35,26 @@
23
35
  },
24
36
  "./package.json": "./package.json"
25
37
  },
38
+ "sideEffects": false,
26
39
  "files": [
27
40
  "dist",
28
41
  "src"
29
42
  ],
30
- "main": "dist/cjs/index.cjs",
31
- "module": "dist/esm/index.js",
43
+ "dependencies": {
44
+ "fractional-indexing": "^3.2.0",
45
+ "sorted-btree": "^1.8.1"
46
+ },
32
47
  "peerDependencies": {
33
48
  "typescript": ">=4.7"
34
49
  },
35
- "author": "Sam Willis",
36
- "license": "MIT",
37
- "repository": {
38
- "type": "git",
39
- "url": "https://github.com/TanStack/db.git",
40
- "directory": "packages/db-ivm"
50
+ "devDependencies": {
51
+ "@types/debug": "^4.1.12",
52
+ "@vitest/coverage-istanbul": "^3.2.4"
41
53
  },
42
- "homepage": "https://tanstack.com/db",
43
- "keywords": [
44
- "electric",
45
- "sql",
46
- "optimistic",
47
- "typescript",
48
- "ivm",
49
- "differential-dataflow"
50
- ],
51
- "sideEffects": false,
52
- "type": "module",
53
- "types": "dist/esm/index.d.ts",
54
54
  "scripts": {
55
55
  "build": "vite build",
56
56
  "dev": "vite build --watch",
57
57
  "lint": "eslint . --fix",
58
- "test": "npx vitest --run"
58
+ "test": "vitest --run"
59
59
  }
60
60
  }
package/src/d2.ts CHANGED
@@ -1,11 +1,11 @@
1
- import { DifferenceStreamWriter } from "./graph.js"
1
+ import { DifferenceStreamWriter } from './graph.js'
2
2
  import type {
3
3
  BinaryOperator,
4
4
  DifferenceStreamReader,
5
5
  UnaryOperator,
6
- } from "./graph.js"
7
- import type { MultiSet, MultiSetArray } from "./multiset.js"
8
- import type { ID2, IStreamBuilder, PipedOperator } from "./types.js"
6
+ } from './graph.js'
7
+ import type { MultiSet, MultiSetArray } from './multiset.js'
8
+ import type { ID2, IStreamBuilder, PipedOperator } from './types.js'
9
9
 
10
10
  export class D2 implements ID2 {
11
11
  #operators: Array<UnaryOperator<any> | BinaryOperator<any>> = []
package/src/graph.ts CHANGED
@@ -1,10 +1,10 @@
1
- import { MultiSet } from "./multiset.js"
2
- import type { MultiSetArray } from "./multiset.js"
1
+ import { MultiSet } from './multiset.js'
2
+ import type { MultiSetArray } from './multiset.js'
3
3
  import type {
4
4
  IDifferenceStreamReader,
5
5
  IDifferenceStreamWriter,
6
6
  IOperator,
7
- } from "./types.js"
7
+ } from './types.js'
8
8
 
9
9
  /**
10
10
  * A read handle to a dataflow edge that receives data from a writer.
@@ -61,7 +61,7 @@ export abstract class Operator<T> implements IOperator<T> {
61
61
  constructor(
62
62
  public id: number,
63
63
  inputs: Array<DifferenceStreamReader<T>>,
64
- output: DifferenceStreamWriter<T>
64
+ output: DifferenceStreamWriter<T>,
65
65
  ) {
66
66
  this.inputs = inputs
67
67
  this.output = output
@@ -84,7 +84,7 @@ export abstract class UnaryOperator<Tin, Tout = Tin> extends Operator<
84
84
  constructor(
85
85
  public id: number,
86
86
  inputA: DifferenceStreamReader<Tin>,
87
- output: DifferenceStreamWriter<Tout>
87
+ output: DifferenceStreamWriter<Tout>,
88
88
  ) {
89
89
  super(id, [inputA], output)
90
90
  }
@@ -103,7 +103,7 @@ export abstract class BinaryOperator<T> extends Operator<T> {
103
103
  public id: number,
104
104
  inputA: DifferenceStreamReader<T>,
105
105
  inputB: DifferenceStreamReader<T>,
106
- output: DifferenceStreamWriter<T>
106
+ output: DifferenceStreamWriter<T>,
107
107
  ) {
108
108
  super(id, [inputA, inputB], output)
109
109
  }
@@ -1,5 +1,5 @@
1
- import { MurmurHashStream, randomHash } from "./murmur.js"
2
- import type { Hasher } from "./murmur.js"
1
+ import { MurmurHashStream, randomHash } from './murmur.js'
2
+ import type { Hasher } from './murmur.js'
3
3
 
4
4
  /*
5
5
  * Implementation of structural hashing based on the Composites polyfill implementation:
@@ -150,7 +150,7 @@ function updateHasher(hasher: Hasher, input: unknown): void {
150
150
  return
151
151
  default:
152
152
  console.warn(
153
- `Ignored input during hashing because it is of type ${typeof input} which is not supported`
153
+ `Ignored input during hashing because it is of type ${typeof input} which is not supported`,
154
154
  )
155
155
  }
156
156
  }
@@ -1,2 +1,2 @@
1
- export { hash } from "./hash.js"
2
- export type { Hash, Hasher } from "./murmur.js"
1
+ export { hash } from './hash.js'
2
+ export type { Hash, Hasher } from './murmur.js'
package/src/index.ts CHANGED
@@ -1,4 +1,5 @@
1
- export * from "./d2.js"
2
- export * from "./multiset.js"
3
- export * from "./operators/index.js"
4
- export * from "./types.js"
1
+ export * from './d2.js'
2
+ export * from './multiset.js'
3
+ export * from './operators/index.js'
4
+ export * from './types.js'
5
+ export { compareKeys, serializeValue } from './utils.js'