@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,137 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const fractionalIndexing = require("fractional-indexing");
4
+ const utils = require("../utils.cjs");
5
+ function indexedValue(value, index) {
6
+ return [value, index];
7
+ }
8
+ function getValue(indexedVal) {
9
+ return indexedVal[0];
10
+ }
11
+ function getIndex(indexedVal) {
12
+ return indexedVal[1];
13
+ }
14
+ function createKeyedComparator(comparator) {
15
+ return ([aKey, aVal], [bKey, bVal]) => {
16
+ const valueComparison = comparator(aVal, bVal);
17
+ if (valueComparison !== 0) {
18
+ return valueComparison;
19
+ }
20
+ return utils.compareKeys(aKey, bKey);
21
+ };
22
+ }
23
+ class TopKArray {
24
+ #sortedValues = [];
25
+ #comparator;
26
+ #topKStart;
27
+ #topKEnd;
28
+ constructor(offset, limit, comparator) {
29
+ this.#topKStart = offset;
30
+ this.#topKEnd = offset + limit;
31
+ this.#comparator = comparator;
32
+ }
33
+ get size() {
34
+ const offset = this.#topKStart;
35
+ const limit = this.#topKEnd - this.#topKStart;
36
+ const available = this.#sortedValues.length - offset;
37
+ return Math.max(0, Math.min(limit, available));
38
+ }
39
+ /**
40
+ * Moves the topK window
41
+ */
42
+ move({
43
+ offset,
44
+ limit
45
+ }) {
46
+ const oldOffset = this.#topKStart;
47
+ const oldLimit = this.#topKEnd - this.#topKStart;
48
+ const oldRange = [
49
+ this.#topKStart,
50
+ this.#topKEnd === Infinity ? this.#topKStart + this.size : this.#topKEnd
51
+ ];
52
+ this.#topKStart = offset ?? oldOffset;
53
+ this.#topKEnd = this.#topKStart + (limit ?? oldLimit);
54
+ const newRange = [
55
+ this.#topKStart,
56
+ this.#topKEnd === Infinity ? Math.max(this.#topKStart + this.size, oldRange[1]) : this.#topKEnd
57
+ ];
58
+ const { onlyInA, onlyInB } = utils.diffHalfOpen(oldRange, newRange);
59
+ const moveIns = [];
60
+ onlyInB.forEach((index) => {
61
+ const value = this.#sortedValues[index];
62
+ if (value) {
63
+ moveIns.push(value);
64
+ }
65
+ });
66
+ const moveOuts = [];
67
+ onlyInA.forEach((index) => {
68
+ const value = this.#sortedValues[index];
69
+ if (value) {
70
+ moveOuts.push(value);
71
+ }
72
+ });
73
+ return { moveIns, moveOuts, changes: onlyInA.length + onlyInB.length > 0 };
74
+ }
75
+ insert(value) {
76
+ const result = { moveIn: null, moveOut: null };
77
+ const index = this.#findIndex(value);
78
+ const indexBefore = index === 0 ? null : getIndex(this.#sortedValues[index - 1]);
79
+ const indexAfter = index === this.#sortedValues.length ? null : getIndex(this.#sortedValues[index]);
80
+ const fractionalIndex = fractionalIndexing.generateKeyBetween(indexBefore, indexAfter);
81
+ const val = indexedValue(value, fractionalIndex);
82
+ this.#sortedValues.splice(index, 0, val);
83
+ if (index < this.#topKEnd) {
84
+ const moveInIndex = Math.max(index, this.#topKStart);
85
+ if (moveInIndex < this.#sortedValues.length) {
86
+ result.moveIn = this.#sortedValues[moveInIndex];
87
+ if (this.#topKEnd < this.#sortedValues.length) {
88
+ result.moveOut = this.#sortedValues[this.#topKEnd];
89
+ }
90
+ }
91
+ }
92
+ return result;
93
+ }
94
+ /**
95
+ * Deletes a value that may or may not be in the topK.
96
+ * IMPORTANT: this assumes that the value is present in the collection
97
+ * if it's not the case it will remove the element
98
+ * that is on the position where the provided `value` would be.
99
+ */
100
+ delete(value) {
101
+ const result = { moveIn: null, moveOut: null };
102
+ const index = this.#findIndex(value);
103
+ const [removedElem] = this.#sortedValues.splice(index, 1);
104
+ if (index < this.#topKEnd) {
105
+ result.moveOut = removedElem;
106
+ if (index < this.#topKStart) {
107
+ const moveOutIndex = this.#topKStart - 1;
108
+ if (moveOutIndex < this.#sortedValues.length) {
109
+ result.moveOut = this.#sortedValues[moveOutIndex];
110
+ } else {
111
+ result.moveOut = null;
112
+ }
113
+ }
114
+ const moveInIndex = this.#topKEnd - 1;
115
+ if (moveInIndex < this.#sortedValues.length) {
116
+ result.moveIn = this.#sortedValues[moveInIndex];
117
+ }
118
+ }
119
+ return result;
120
+ }
121
+ // TODO: see if there is a way to refactor the code for insert and delete in the topK above
122
+ // because they are very similar, one is shifting the topK window to the left and the other is shifting it to the right
123
+ // so i have the feeling there is a common pattern here and we can implement both cases using that pattern
124
+ #findIndex(value) {
125
+ return utils.binarySearch(
126
+ this.#sortedValues,
127
+ indexedValue(value, ``),
128
+ (a, b) => this.#comparator(getValue(a), getValue(b))
129
+ );
130
+ }
131
+ }
132
+ exports.TopKArray = TopKArray;
133
+ exports.createKeyedComparator = createKeyedComparator;
134
+ exports.getIndex = getIndex;
135
+ exports.getValue = getValue;
136
+ exports.indexedValue = indexedValue;
137
+ //# sourceMappingURL=topKArray.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"topKArray.cjs","sources":["../../../src/operators/topKArray.ts"],"sourcesContent":["import { generateKeyBetween } from 'fractional-indexing'\nimport { binarySearch, compareKeys, diffHalfOpen } from '../utils.js'\nimport type { HRange } from '../utils.js'\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\n/**\n * Creates a comparator for [key, value] tuples that first compares values,\n * then uses the row key as a stable tie-breaker.\n */\nexport function createKeyedComparator<K extends string | number, T>(\n comparator: (a: T, b: T) => number,\n): (a: [K, T], b: [K, T]) => number {\n return ([aKey, aVal], [bKey, bVal]) => {\n // First compare on the value\n const valueComparison = comparator(aVal, bVal)\n if (valueComparison !== 0) {\n return valueComparison\n }\n // If the values are equal, use the row key as tie-breaker\n // This provides stable, deterministic ordering since keys are string | number\n return compareKeys(aKey, bKey)\n }\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 */\nexport class 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"],"names":["compareKeys","diffHalfOpen","generateKeyBetween","binarySearch"],"mappings":";;;;AAQO,SAAS,aACd,OACA,OACiB;AACjB,SAAO,CAAC,OAAO,KAAK;AACtB;AAEO,SAAS,SAAY,YAAg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,QAAQ,KAAK,WAAW,KAAK;AAEnC,UAAM,CAAC,WAAW,IAAI,KAAK,cAAc,OAAO,OAAO,CAAC;AAGxD,QAAI,QAAQ,KAAK,UAAU;AAIzB,aAAO,UAAU;AACjB,UAAI,QAAQ,KAAK,YAAY;AAM3B,cAAM,eAAe,KAAK,aAAa;AACvC,YAAI,eAAe,KAAK,cAAc,QAAQ;AAC5C,iBAAO,UAAU,KAAK,cAAc,YAAY;AAAA,QAClD,OAAO;AAGL,iBAAO,UAAU;AAAA,QACnB;AAAA,MACF;AAKA,YAAM,cAAc,KAAK,WAAW;AACpC,UAAI,cAAc,KAAK,cAAc,QAAQ;AAC3C,eAAO,SAAS,KAAK,cAAc,WAAW;AAAA,MAChD;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA,EAMA,WAAW,OAAkB;AAC3B,WAAOC,MAAAA;AAAAA,MAAa,KAAK;AAAA,MAAe,aAAa,OAAO,EAAE;AAAA,MAAG,CAAC,GAAG,MACnE,KAAK,YAAY,SAAS,CAAC,GAAG,SAAS,CAAC,CAAC;AAAA,IAAA;AAAA,EAE7C;AACF;;;;;;"}
@@ -0,0 +1,59 @@
1
+ export type FractionalIndex = string;
2
+ export type IndexedValue<V> = [V, FractionalIndex];
3
+ export declare function indexedValue<V>(value: V, index: FractionalIndex): IndexedValue<V>;
4
+ export declare function getValue<V>(indexedVal: IndexedValue<V>): V;
5
+ export declare function getIndex<V>(indexedVal: IndexedValue<V>): FractionalIndex;
6
+ /**
7
+ * Creates a comparator for [key, value] tuples that first compares values,
8
+ * then uses the row key as a stable tie-breaker.
9
+ */
10
+ export declare function createKeyedComparator<K extends string | number, T>(comparator: (a: T, b: T) => number): (a: [K, T], b: [K, T]) => number;
11
+ export type TopKChanges<V> = {
12
+ /** Indicates which element moves into the topK (if any) */
13
+ moveIn: IndexedValue<V> | null;
14
+ /** Indicates which element moves out of the topK (if any) */
15
+ moveOut: IndexedValue<V> | null;
16
+ };
17
+ export type TopKMoveChanges<V> = {
18
+ /** Flag that marks whether there were any changes to the topK */
19
+ changes: boolean;
20
+ /** Indicates which elements move into the topK (if any) */
21
+ moveIns: Array<IndexedValue<V>>;
22
+ /** Indicates which elements move out of the topK (if any) */
23
+ moveOuts: Array<IndexedValue<V>>;
24
+ };
25
+ /**
26
+ * A topK data structure that supports insertions and deletions
27
+ * and returns changes to the topK.
28
+ */
29
+ export interface TopK<V> {
30
+ size: number;
31
+ insert: (value: V) => TopKChanges<V>;
32
+ delete: (value: V) => TopKChanges<V>;
33
+ }
34
+ /**
35
+ * Implementation of a topK data structure.
36
+ * Uses a sorted array internally to store the values and keeps a topK window over that array.
37
+ * Inserts and deletes are O(n) operations because worst case an element is inserted/deleted
38
+ * at the start of the array which causes all the elements to shift to the right/left.
39
+ */
40
+ export declare class TopKArray<V> implements TopK<V> {
41
+ #private;
42
+ constructor(offset: number, limit: number, comparator: (a: V, b: V) => number);
43
+ get size(): number;
44
+ /**
45
+ * Moves the topK window
46
+ */
47
+ move({ offset, limit, }: {
48
+ offset?: number;
49
+ limit?: number;
50
+ }): TopKMoveChanges<V>;
51
+ insert(value: V): TopKChanges<V>;
52
+ /**
53
+ * Deletes a value that may or may not be in the topK.
54
+ * IMPORTANT: this assumes that the value is present in the collection
55
+ * if it's not the case it will remove the element
56
+ * that is on the position where the provided `value` would be.
57
+ */
58
+ delete(value: V): TopKChanges<V>;
59
+ }
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const topKArray = require("./topKArray.cjs");
4
+ class TopKState {
5
+ #multiplicities = /* @__PURE__ */ new Map();
6
+ #topK;
7
+ constructor(topK) {
8
+ this.#topK = topK;
9
+ }
10
+ get size() {
11
+ return this.#topK.size;
12
+ }
13
+ get isEmpty() {
14
+ return this.#multiplicities.size === 0 && this.#topK.size === 0;
15
+ }
16
+ /**
17
+ * Process an element update (insert or delete based on multiplicity change).
18
+ * Returns the changes to the topK window.
19
+ */
20
+ processElement(key, value, multiplicity) {
21
+ const { oldMultiplicity, newMultiplicity } = this.#updateMultiplicity(
22
+ key,
23
+ multiplicity
24
+ );
25
+ if (oldMultiplicity <= 0 && newMultiplicity > 0) {
26
+ return this.#topK.insert([key, value]);
27
+ } else if (oldMultiplicity > 0 && newMultiplicity <= 0) {
28
+ return this.#topK.delete([key, value]);
29
+ }
30
+ return { moveIn: null, moveOut: null };
31
+ }
32
+ /**
33
+ * Move the topK window. Only works with TopKArray implementation.
34
+ */
35
+ move(options) {
36
+ if (!(this.#topK instanceof topKArray.TopKArray)) {
37
+ throw new Error(
38
+ `Cannot move B+-tree implementation of TopK with fractional index`
39
+ );
40
+ }
41
+ return this.#topK.move(options);
42
+ }
43
+ #updateMultiplicity(key, multiplicity) {
44
+ if (multiplicity === 0) {
45
+ const current = this.#multiplicities.get(key) ?? 0;
46
+ return { oldMultiplicity: current, newMultiplicity: current };
47
+ }
48
+ const oldMultiplicity = this.#multiplicities.get(key) ?? 0;
49
+ const newMultiplicity = oldMultiplicity + multiplicity;
50
+ if (newMultiplicity === 0) {
51
+ this.#multiplicities.delete(key);
52
+ } else {
53
+ this.#multiplicities.set(key, newMultiplicity);
54
+ }
55
+ return { oldMultiplicity, newMultiplicity };
56
+ }
57
+ }
58
+ function handleMoveIn(moveIn, result) {
59
+ if (moveIn) {
60
+ const [[key, value], index] = moveIn;
61
+ result.push([[key, [value, index]], 1]);
62
+ }
63
+ }
64
+ function handleMoveOut(moveOut, result) {
65
+ if (moveOut) {
66
+ const [[key, value], index] = moveOut;
67
+ result.push([[key, [value, index]], -1]);
68
+ }
69
+ }
70
+ exports.TopKState = TopKState;
71
+ exports.handleMoveIn = handleMoveIn;
72
+ exports.handleMoveOut = handleMoveOut;
73
+ //# sourceMappingURL=topKState.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"topKState.cjs","sources":["../../../src/operators/topKState.ts"],"sourcesContent":["import { TopKArray } from './topKArray.js'\nimport type {\n IndexedValue,\n TopK,\n TopKChanges,\n TopKMoveChanges,\n} from './topKArray.js'\n\n/**\n * Helper class that manages the state for a single topK window.\n * Encapsulates the multiplicity tracking and topK data structure,\n * providing a clean interface for processing elements and moving the window.\n *\n * This class is used by both TopKWithFractionalIndexOperator (single instance)\n * and GroupedTopKWithFractionalIndexOperator (one instance per group).\n */\nexport class TopKState<K extends string | number, T> {\n #multiplicities: Map<K, number> = new Map()\n #topK: TopK<[K, T]>\n\n constructor(topK: TopK<[K, T]>) {\n this.#topK = topK\n }\n\n get size(): number {\n return this.#topK.size\n }\n\n get isEmpty(): boolean {\n return this.#multiplicities.size === 0 && this.#topK.size === 0\n }\n\n /**\n * Process an element update (insert or delete based on multiplicity change).\n * Returns the changes to the topK window.\n */\n processElement(key: K, value: T, multiplicity: number): TopKChanges<[K, T]> {\n const { oldMultiplicity, newMultiplicity } = this.#updateMultiplicity(\n key,\n multiplicity,\n )\n\n if (oldMultiplicity <= 0 && newMultiplicity > 0) {\n // The value was invisible but should now be visible\n return this.#topK.insert([key, value])\n } else if (oldMultiplicity > 0 && newMultiplicity <= 0) {\n // The value was visible but should now be invisible\n return this.#topK.delete([key, value])\n }\n // The value was invisible and remains invisible,\n // or was visible and remains visible - no topK change\n return { moveIn: null, moveOut: null }\n }\n\n /**\n * Move the topK window. Only works with TopKArray implementation.\n */\n move(options: { offset?: number; limit?: number }): TopKMoveChanges<[K, T]> {\n if (!(this.#topK instanceof TopKArray)) {\n throw new Error(\n `Cannot move B+-tree implementation of TopK with fractional index`,\n )\n }\n return this.#topK.move(options)\n }\n\n #updateMultiplicity(\n key: K,\n multiplicity: number,\n ): { oldMultiplicity: number; newMultiplicity: number } {\n if (multiplicity === 0) {\n const current = this.#multiplicities.get(key) ?? 0\n return { oldMultiplicity: current, newMultiplicity: current }\n }\n\n const oldMultiplicity = this.#multiplicities.get(key) ?? 0\n const newMultiplicity = oldMultiplicity + multiplicity\n if (newMultiplicity === 0) {\n this.#multiplicities.delete(key)\n } else {\n this.#multiplicities.set(key, newMultiplicity)\n }\n return { oldMultiplicity, newMultiplicity }\n }\n}\n\n/**\n * Handles a moveIn change by adding it to the result array.\n */\nexport function handleMoveIn<K extends string | number, T>(\n moveIn: IndexedValue<[K, T]> | null,\n result: Array<[[K, IndexedValue<T>], number]>,\n): void {\n if (moveIn) {\n const [[key, value], index] = moveIn\n result.push([[key, [value, index]], 1])\n }\n}\n\n/**\n * Handles a moveOut change by adding it to the result array.\n */\nexport function handleMoveOut<K extends string | number, T>(\n moveOut: IndexedValue<[K, T]> | null,\n result: Array<[[K, IndexedValue<T>], number]>,\n): void {\n if (moveOut) {\n const [[key, value], index] = moveOut\n result.push([[key, [value, index]], -1])\n }\n}\n"],"names":["TopKArray"],"mappings":";;;AAgBO,MAAM,UAAwC;AAAA,EACnD,sCAAsC,IAAA;AAAA,EACtC;AAAA,EAEA,YAAY,MAAoB;AAC9B,SAAK,QAAQ;AAAA,EACf;AAAA,EAEA,IAAI,OAAe;AACjB,WAAO,KAAK,MAAM;AAAA,EACpB;AAAA,EAEA,IAAI,UAAmB;AACrB,WAAO,KAAK,gBAAgB,SAAS,KAAK,KAAK,MAAM,SAAS;AAAA,EAChE;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,eAAe,KAAQ,OAAU,cAA2C;AAC1E,UAAM,EAAE,iBAAiB,gBAAA,IAAoB,KAAK;AAAA,MAChD;AAAA,MACA;AAAA,IAAA;AAGF,QAAI,mBAAmB,KAAK,kBAAkB,GAAG;AAE/C,aAAO,KAAK,MAAM,OAAO,CAAC,KAAK,KAAK,CAAC;AAAA,IACvC,WAAW,kBAAkB,KAAK,mBAAmB,GAAG;AAEtD,aAAO,KAAK,MAAM,OAAO,CAAC,KAAK,KAAK,CAAC;AAAA,IACvC;AAGA,WAAO,EAAE,QAAQ,MAAM,SAAS,KAAA;AAAA,EAClC;AAAA;AAAA;AAAA;AAAA,EAKA,KAAK,SAAuE;AAC1E,QAAI,EAAE,KAAK,iBAAiBA,UAAAA,YAAY;AACtC,YAAM,IAAI;AAAA,QACR;AAAA,MAAA;AAAA,IAEJ;AACA,WAAO,KAAK,MAAM,KAAK,OAAO;AAAA,EAChC;AAAA,EAEA,oBACE,KACA,cACsD;AACtD,QAAI,iBAAiB,GAAG;AACtB,YAAM,UAAU,KAAK,gBAAgB,IAAI,GAAG,KAAK;AACjD,aAAO,EAAE,iBAAiB,SAAS,iBAAiB,QAAA;AAAA,IACtD;AAEA,UAAM,kBAAkB,KAAK,gBAAgB,IAAI,GAAG,KAAK;AACzD,UAAM,kBAAkB,kBAAkB;AAC1C,QAAI,oBAAoB,GAAG;AACzB,WAAK,gBAAgB,OAAO,GAAG;AAAA,IACjC,OAAO;AACL,WAAK,gBAAgB,IAAI,KAAK,eAAe;AAAA,IAC/C;AACA,WAAO,EAAE,iBAAiB,gBAAA;AAAA,EAC5B;AACF;AAKO,SAAS,aACd,QACA,QACM;AACN,MAAI,QAAQ;AACV,UAAM,CAAC,CAAC,KAAK,KAAK,GAAG,KAAK,IAAI;AAC9B,WAAO,KAAK,CAAC,CAAC,KAAK,CAAC,OAAO,KAAK,CAAC,GAAG,CAAC,CAAC;AAAA,EACxC;AACF;AAKO,SAAS,cACd,SACA,QACM;AACN,MAAI,SAAS;AACX,UAAM,CAAC,CAAC,KAAK,KAAK,GAAG,KAAK,IAAI;AAC9B,WAAO,KAAK,CAAC,CAAC,KAAK,CAAC,OAAO,KAAK,CAAC,GAAG,EAAE,CAAC;AAAA,EACzC;AACF;;;;"}
@@ -0,0 +1,35 @@
1
+ import { IndexedValue, TopK, TopKChanges, TopKMoveChanges } from './topKArray.js';
2
+ /**
3
+ * Helper class that manages the state for a single topK window.
4
+ * Encapsulates the multiplicity tracking and topK data structure,
5
+ * providing a clean interface for processing elements and moving the window.
6
+ *
7
+ * This class is used by both TopKWithFractionalIndexOperator (single instance)
8
+ * and GroupedTopKWithFractionalIndexOperator (one instance per group).
9
+ */
10
+ export declare class TopKState<K extends string | number, T> {
11
+ #private;
12
+ constructor(topK: TopK<[K, T]>);
13
+ get size(): number;
14
+ get isEmpty(): boolean;
15
+ /**
16
+ * Process an element update (insert or delete based on multiplicity change).
17
+ * Returns the changes to the topK window.
18
+ */
19
+ processElement(key: K, value: T, multiplicity: number): TopKChanges<[K, T]>;
20
+ /**
21
+ * Move the topK window. Only works with TopKArray implementation.
22
+ */
23
+ move(options: {
24
+ offset?: number;
25
+ limit?: number;
26
+ }): TopKMoveChanges<[K, T]>;
27
+ }
28
+ /**
29
+ * Handles a moveIn change by adding it to the result array.
30
+ */
31
+ export declare function handleMoveIn<K extends string | number, T>(moveIn: IndexedValue<[K, T]> | null, result: Array<[[K, IndexedValue<T>], number]>): void;
32
+ /**
33
+ * Handles a moveOut change by adding it to the result array.
34
+ */
35
+ export declare function handleMoveOut<K extends string | number, T>(moveOut: IndexedValue<[K, T]> | null, result: Array<[[K, IndexedValue<T>], number]>): void;
@@ -1,157 +1,37 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const fractionalIndexing = require("fractional-indexing");
4
3
  const graph = require("../graph.cjs");
5
4
  const d2 = require("../d2.cjs");
6
5
  const multiset = require("../multiset.cjs");
7
- const utils = require("../utils.cjs");
8
- class TopKArray {
9
- #sortedValues = [];
10
- #comparator;
11
- #topKStart;
12
- #topKEnd;
13
- constructor(offset, limit, comparator) {
14
- this.#topKStart = offset;
15
- this.#topKEnd = offset + limit;
16
- this.#comparator = comparator;
17
- }
18
- get size() {
19
- const offset = this.#topKStart;
20
- const limit = this.#topKEnd - this.#topKStart;
21
- const available = this.#sortedValues.length - offset;
22
- return Math.max(0, Math.min(limit, available));
23
- }
24
- /**
25
- * Moves the topK window
26
- */
27
- move({
28
- offset,
29
- limit
30
- }) {
31
- const oldOffset = this.#topKStart;
32
- const oldLimit = this.#topKEnd - this.#topKStart;
33
- const oldRange = [
34
- this.#topKStart,
35
- this.#topKEnd === Infinity ? this.#topKStart + this.size : this.#topKEnd
36
- ];
37
- this.#topKStart = offset ?? oldOffset;
38
- this.#topKEnd = this.#topKStart + (limit ?? oldLimit);
39
- const newRange = [
40
- this.#topKStart,
41
- this.#topKEnd === Infinity ? Math.max(this.#topKStart + this.size, oldRange[1]) : this.#topKEnd
42
- ];
43
- const { onlyInA, onlyInB } = utils.diffHalfOpen(oldRange, newRange);
44
- const moveIns = [];
45
- onlyInB.forEach((index) => {
46
- const value = this.#sortedValues[index];
47
- if (value) {
48
- moveIns.push(value);
49
- }
50
- });
51
- const moveOuts = [];
52
- onlyInA.forEach((index) => {
53
- const value = this.#sortedValues[index];
54
- if (value) {
55
- moveOuts.push(value);
56
- }
57
- });
58
- return { moveIns, moveOuts, changes: onlyInA.length + onlyInB.length > 0 };
59
- }
60
- insert(value) {
61
- const result = { moveIn: null, moveOut: null };
62
- const index = this.#findIndex(value);
63
- const indexBefore = index === 0 ? null : getIndex(this.#sortedValues[index - 1]);
64
- const indexAfter = index === this.#sortedValues.length ? null : getIndex(this.#sortedValues[index]);
65
- const fractionalIndex = fractionalIndexing.generateKeyBetween(indexBefore, indexAfter);
66
- const val = indexedValue(value, fractionalIndex);
67
- this.#sortedValues.splice(index, 0, val);
68
- if (index < this.#topKEnd) {
69
- const moveInIndex = Math.max(index, this.#topKStart);
70
- if (moveInIndex < this.#sortedValues.length) {
71
- result.moveIn = this.#sortedValues[moveInIndex];
72
- if (this.#topKEnd < this.#sortedValues.length) {
73
- result.moveOut = this.#sortedValues[this.#topKEnd];
74
- }
75
- }
76
- }
77
- return result;
78
- }
79
- /**
80
- * Deletes a value that may or may not be in the topK.
81
- * IMPORTANT: this assumes that the value is present in the collection
82
- * if it's not the case it will remove the element
83
- * that is on the position where the provided `value` would be.
84
- */
85
- delete(value) {
86
- const result = { moveIn: null, moveOut: null };
87
- const index = this.#findIndex(value);
88
- const [removedElem] = this.#sortedValues.splice(index, 1);
89
- if (index < this.#topKEnd) {
90
- result.moveOut = removedElem;
91
- if (index < this.#topKStart) {
92
- const moveOutIndex = this.#topKStart - 1;
93
- if (moveOutIndex < this.#sortedValues.length) {
94
- result.moveOut = this.#sortedValues[moveOutIndex];
95
- } else {
96
- result.moveOut = null;
97
- }
98
- }
99
- const moveInIndex = this.#topKEnd - 1;
100
- if (moveInIndex < this.#sortedValues.length) {
101
- result.moveIn = this.#sortedValues[moveInIndex];
102
- }
103
- }
104
- return result;
105
- }
106
- // TODO: see if there is a way to refactor the code for insert and delete in the topK above
107
- // because they are very similar, one is shifting the topK window to the left and the other is shifting it to the right
108
- // so i have the feeling there is a common pattern here and we can implement both cases using that pattern
109
- #findIndex(value) {
110
- return utils.binarySearch(
111
- this.#sortedValues,
112
- indexedValue(value, ``),
113
- (a, b) => this.#comparator(getValue(a), getValue(b))
114
- );
115
- }
116
- }
6
+ const topKState = require("./topKState.cjs");
7
+ const topKArray = require("./topKArray.cjs");
117
8
  class TopKWithFractionalIndexOperator extends graph.UnaryOperator {
118
- #index = /* @__PURE__ */ new Map();
119
- // maps keys to their multiplicity
120
- /**
121
- * topK data structure that supports insertions and deletions
122
- * and returns changes to the topK.
123
- * Elements are stored as [key, value] tuples for stable tie-breaking.
124
- */
125
- #topK;
9
+ #state;
126
10
  constructor(id, inputA, output, comparator, options) {
127
11
  super(id, inputA, output);
128
12
  const limit = options.limit ?? Infinity;
129
13
  const offset = options.offset ?? 0;
130
- this.#topK = this.createTopK(
14
+ const topK = this.createTopK(
131
15
  offset,
132
16
  limit,
133
- createKeyedComparator(comparator)
17
+ topKArray.createKeyedComparator(comparator)
134
18
  );
135
- options.setSizeCallback?.(() => this.#topK.size);
19
+ this.#state = new topKState.TopKState(topK);
20
+ options.setSizeCallback?.(() => this.#state.size);
136
21
  options.setWindowFn?.(this.moveTopK.bind(this));
137
22
  }
138
23
  createTopK(offset, limit, comparator) {
139
- return new TopKArray(offset, limit, comparator);
24
+ return new topKArray.TopKArray(offset, limit, comparator);
140
25
  }
141
26
  /**
142
27
  * Moves the topK window based on the provided offset and limit.
143
28
  * Any changes to the topK are sent to the output.
144
29
  */
145
30
  moveTopK({ offset, limit }) {
146
- if (!(this.#topK instanceof TopKArray)) {
147
- throw new Error(
148
- `Cannot move B+-tree implementation of TopK with fractional index`
149
- );
150
- }
151
31
  const result = [];
152
- const diff = this.#topK.move({ offset, limit });
153
- diff.moveIns.forEach((moveIn) => this.handleMoveIn(moveIn, result));
154
- diff.moveOuts.forEach((moveOut) => this.handleMoveOut(moveOut, result));
32
+ const diff = this.#state.move({ offset, limit });
33
+ diff.moveIns.forEach((moveIn) => topKState.handleMoveIn(moveIn, result));
34
+ diff.moveOuts.forEach((moveOut) => topKState.handleMoveOut(moveOut, result));
155
35
  if (diff.changes) {
156
36
  this.output.sendData(new multiset.MultiSet(result));
157
37
  }
@@ -169,44 +49,9 @@ class TopKWithFractionalIndexOperator extends graph.UnaryOperator {
169
49
  }
170
50
  }
171
51
  processElement(key, value, multiplicity, result) {
172
- const { oldMultiplicity, newMultiplicity } = this.addKey(key, multiplicity);
173
- let res = {
174
- moveIn: null,
175
- moveOut: null
176
- };
177
- if (oldMultiplicity <= 0 && newMultiplicity > 0) {
178
- res = this.#topK.insert([key, value]);
179
- } else if (oldMultiplicity > 0 && newMultiplicity <= 0) {
180
- res = this.#topK.delete([key, value]);
181
- } else ;
182
- this.handleMoveIn(res.moveIn, result);
183
- this.handleMoveOut(res.moveOut, result);
184
- return;
185
- }
186
- handleMoveIn(moveIn, result) {
187
- if (moveIn) {
188
- const [[key, value], index] = moveIn;
189
- result.push([[key, [value, index]], 1]);
190
- }
191
- }
192
- handleMoveOut(moveOut, result) {
193
- if (moveOut) {
194
- const [[key, value], index] = moveOut;
195
- result.push([[key, [value, index]], -1]);
196
- }
197
- }
198
- getMultiplicity(key) {
199
- return this.#index.get(key) ?? 0;
200
- }
201
- addKey(key, multiplicity) {
202
- const oldMultiplicity = this.getMultiplicity(key);
203
- const newMultiplicity = oldMultiplicity + multiplicity;
204
- if (newMultiplicity === 0) {
205
- this.#index.delete(key);
206
- } else {
207
- this.#index.set(key, newMultiplicity);
208
- }
209
- return { oldMultiplicity, newMultiplicity };
52
+ const changes = this.#state.processElement(key, value, multiplicity);
53
+ topKState.handleMoveIn(changes.moveIn, result);
54
+ topKState.handleMoveOut(changes.moveOut, result);
210
55
  }
211
56
  }
212
57
  function topKWithFractionalIndex(comparator, options) {
@@ -227,27 +72,6 @@ function topKWithFractionalIndex(comparator, options) {
227
72
  return output;
228
73
  };
229
74
  }
230
- function indexedValue(value, index) {
231
- return [value, index];
232
- }
233
- function getValue(indexedVal) {
234
- return indexedVal[0];
235
- }
236
- function getIndex(indexedVal) {
237
- return indexedVal[1];
238
- }
239
- function createKeyedComparator(comparator) {
240
- return ([aKey, aVal], [bKey, bVal]) => {
241
- const valueComparison = comparator(aVal, bVal);
242
- if (valueComparison !== 0) {
243
- return valueComparison;
244
- }
245
- return utils.compareKeys(aKey, bKey);
246
- };
247
- }
248
75
  exports.TopKWithFractionalIndexOperator = TopKWithFractionalIndexOperator;
249
- exports.getIndex = getIndex;
250
- exports.getValue = getValue;
251
- exports.indexedValue = indexedValue;
252
76
  exports.topKWithFractionalIndex = topKWithFractionalIndex;
253
77
  //# sourceMappingURL=topKWithFractionalIndex.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"topKWithFractionalIndex.cjs","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 { binarySearch, compareKeys, diffHalfOpen } 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<\n K extends string | number,\n T,\n> extends UnaryOperator<[K, T], [K, IndexedValue<T>]> {\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 * Elements are stored as [key, value] tuples for stable tie-breaking.\n */\n #topK: TopK<[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 this.#topK = this.createTopK(\n offset,\n limit,\n createKeyedComparator(comparator),\n )\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: [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 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<[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 res = this.#topK.insert([key, value])\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 res = this.#topK.delete([key, value])\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<[K, T]> | null,\n result: Array<[[K, IndexedValue<T>], number]>,\n ) {\n if (moveIn) {\n const [[key, value], index] = moveIn\n result.push([[key, [value, index]], 1])\n }\n }\n\n private handleMoveOut(\n moveOut: IndexedValue<[K, T]> | null,\n result: Array<[[K, IndexedValue<T>], number]>,\n ) {\n if (moveOut) {\n const [[key, value], index] = moveOut\n result.push([[key, [value, 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 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\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\n/**\n * Creates a comparator for [key, value] tuples that first compares values,\n * then uses the row key as a stable tie-breaker.\n */\nfunction createKeyedComparator<K extends string | number, T>(\n comparator: (a: T, b: T) => number,\n): (a: [K, T], b: [K, T]) => number {\n return ([aKey, aVal], [bKey, bVal]) => {\n // First compare on the value\n const valueComparison = comparator(aVal, bVal)\n if (valueComparison !== 0) {\n return valueComparison\n }\n // If the values are equal, use the row key as tie-breaker\n // This provides stable, deterministic ordering since keys are string | number\n return compareKeys(aKey, bKey)\n }\n}\n"],"names":["diffHalfOpen","generateKeyBetween","binarySearch","UnaryOperator","MultiSet","StreamBuilder","DifferenceStreamWriter","compareKeys"],"mappings":";;;;;;;AAkDA,MAAM,UAAgC;AAAA,EACpC,gBAAwC,CAAA;AAAA,EACxC;AAAA,EACA;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":3,"file":"topKWithFractionalIndex.cjs","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":["UnaryOperator","createKeyedComparator","TopKState","TopKArray","handleMoveIn","handleMoveOut","MultiSet","StreamBuilder","DifferenceStreamWri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