@tanstack/db-ivm 0.1.9 → 0.1.10

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 (85) hide show
  1. package/dist/cjs/d2.cjs +25 -49
  2. package/dist/cjs/d2.cjs.map +1 -1
  3. package/dist/cjs/graph.cjs +8 -20
  4. package/dist/cjs/graph.cjs.map +1 -1
  5. package/dist/cjs/indexes.cjs +118 -79
  6. package/dist/cjs/indexes.cjs.map +1 -1
  7. package/dist/cjs/indexes.d.cts +23 -0
  8. package/dist/cjs/multiset.cjs +106 -115
  9. package/dist/cjs/multiset.cjs.map +1 -1
  10. package/dist/cjs/multiset.d.cts +1 -0
  11. package/dist/cjs/operators/debug.cjs +5 -15
  12. package/dist/cjs/operators/debug.cjs.map +1 -1
  13. package/dist/cjs/operators/distinct.cjs +11 -22
  14. package/dist/cjs/operators/distinct.cjs.map +1 -1
  15. package/dist/cjs/operators/filter.cjs +3 -12
  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/filterBy.d.cts +1 -2
  19. package/dist/cjs/operators/groupBy.cjs +1 -2
  20. package/dist/cjs/operators/groupBy.cjs.map +1 -1
  21. package/dist/cjs/operators/join.cjs +104 -93
  22. package/dist/cjs/operators/join.cjs.map +1 -1
  23. package/dist/cjs/operators/join.d.cts +11 -8
  24. package/dist/cjs/operators/map.cjs +3 -12
  25. package/dist/cjs/operators/map.cjs.map +1 -1
  26. package/dist/cjs/operators/orderBy.cjs +10 -10
  27. package/dist/cjs/operators/orderBy.cjs.map +1 -1
  28. package/dist/cjs/operators/orderBy.d.cts +1 -2
  29. package/dist/cjs/operators/output.cjs +3 -12
  30. package/dist/cjs/operators/output.cjs.map +1 -1
  31. package/dist/cjs/operators/reduce.cjs +11 -22
  32. package/dist/cjs/operators/reduce.cjs.map +1 -1
  33. package/dist/cjs/operators/tap.cjs +3 -12
  34. package/dist/cjs/operators/tap.cjs.map +1 -1
  35. package/dist/cjs/operators/topK.cjs +4 -4
  36. package/dist/cjs/operators/topK.cjs.map +1 -1
  37. package/dist/cjs/operators/topK.d.cts +1 -2
  38. package/dist/cjs/operators/topKWithFractionalIndex.cjs +56 -75
  39. package/dist/cjs/operators/topKWithFractionalIndex.cjs.map +1 -1
  40. package/dist/esm/d2.js +25 -49
  41. package/dist/esm/d2.js.map +1 -1
  42. package/dist/esm/graph.js +8 -20
  43. package/dist/esm/graph.js.map +1 -1
  44. package/dist/esm/indexes.d.ts +23 -0
  45. package/dist/esm/indexes.js +118 -79
  46. package/dist/esm/indexes.js.map +1 -1
  47. package/dist/esm/multiset.d.ts +1 -0
  48. package/dist/esm/multiset.js +106 -115
  49. package/dist/esm/multiset.js.map +1 -1
  50. package/dist/esm/operators/debug.js +5 -15
  51. package/dist/esm/operators/debug.js.map +1 -1
  52. package/dist/esm/operators/distinct.js +11 -22
  53. package/dist/esm/operators/distinct.js.map +1 -1
  54. package/dist/esm/operators/filter.js +3 -12
  55. package/dist/esm/operators/filter.js.map +1 -1
  56. package/dist/esm/operators/filterBy.d.ts +1 -2
  57. package/dist/esm/operators/filterBy.js.map +1 -1
  58. package/dist/esm/operators/groupBy.js +1 -2
  59. package/dist/esm/operators/groupBy.js.map +1 -1
  60. package/dist/esm/operators/join.d.ts +11 -8
  61. package/dist/esm/operators/join.js +104 -93
  62. package/dist/esm/operators/join.js.map +1 -1
  63. package/dist/esm/operators/map.js +3 -12
  64. package/dist/esm/operators/map.js.map +1 -1
  65. package/dist/esm/operators/orderBy.d.ts +1 -2
  66. package/dist/esm/operators/orderBy.js +10 -10
  67. package/dist/esm/operators/orderBy.js.map +1 -1
  68. package/dist/esm/operators/output.js +3 -12
  69. package/dist/esm/operators/output.js.map +1 -1
  70. package/dist/esm/operators/reduce.js +11 -22
  71. package/dist/esm/operators/reduce.js.map +1 -1
  72. package/dist/esm/operators/tap.js +3 -12
  73. package/dist/esm/operators/tap.js.map +1 -1
  74. package/dist/esm/operators/topK.d.ts +1 -2
  75. package/dist/esm/operators/topK.js +4 -4
  76. package/dist/esm/operators/topK.js.map +1 -1
  77. package/dist/esm/operators/topKWithFractionalIndex.js +56 -75
  78. package/dist/esm/operators/topKWithFractionalIndex.js.map +1 -1
  79. package/package.json +1 -1
  80. package/src/indexes.ts +54 -0
  81. package/src/multiset.ts +6 -0
  82. package/src/operators/filterBy.ts +1 -2
  83. package/src/operators/join.ts +249 -139
  84. package/src/operators/orderBy.ts +1 -2
  85. package/src/operators/topK.ts +1 -2
@@ -1,37 +1,29 @@
1
- var __typeError = (msg) => {
2
- throw TypeError(msg);
3
- };
4
- var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
5
- var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
6
- var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
7
- var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
8
- var _index, _indexOut, _f;
9
1
  import { UnaryOperator, DifferenceStreamWriter } from "../graph.js";
10
2
  import { StreamBuilder } from "../d2.js";
11
3
  import { MultiSet } from "../multiset.js";
12
4
  import { Index } from "../indexes.js";
13
5
  class ReduceOperator extends UnaryOperator {
6
+ #index = new Index();
7
+ #indexOut = new Index();
8
+ #f;
14
9
  constructor(id, inputA, output, f) {
15
10
  super(id, inputA, output);
16
- __privateAdd(this, _index, new Index());
17
- __privateAdd(this, _indexOut, new Index());
18
- __privateAdd(this, _f);
19
- __privateSet(this, _f, f);
11
+ this.#f = f;
20
12
  }
21
13
  run() {
22
14
  const keysTodo = /* @__PURE__ */ new Set();
23
15
  for (const message of this.inputMessages()) {
24
16
  for (const [item, multiplicity] of message.getInner()) {
25
17
  const [key, value] = item;
26
- __privateGet(this, _index).addValue(key, [value, multiplicity]);
18
+ this.#index.addValue(key, [value, multiplicity]);
27
19
  keysTodo.add(key);
28
20
  }
29
21
  }
30
22
  const result = [];
31
23
  for (const key of keysTodo) {
32
- const curr = __privateGet(this, _index).get(key);
33
- const currOut = __privateGet(this, _indexOut).get(key);
34
- const out = __privateGet(this, _f).call(this, curr);
24
+ const curr = this.#index.get(key);
25
+ const currOut = this.#indexOut.get(key);
26
+ const out = this.#f(curr);
35
27
  const newOutputMap = /* @__PURE__ */ new Map();
36
28
  const oldOutputMap = /* @__PURE__ */ new Map();
37
29
  for (const [value, multiplicity] of out) {
@@ -45,14 +37,14 @@ class ReduceOperator extends UnaryOperator {
45
37
  for (const [value, multiplicity] of oldOutputMap) {
46
38
  if (!newOutputMap.has(value)) {
47
39
  result.push([[key, value], -multiplicity]);
48
- __privateGet(this, _indexOut).addValue(key, [value, -multiplicity]);
40
+ this.#indexOut.addValue(key, [value, -multiplicity]);
49
41
  }
50
42
  }
51
43
  for (const [value, multiplicity] of newOutputMap) {
52
44
  if (!oldOutputMap.has(value)) {
53
45
  if (multiplicity !== 0) {
54
46
  result.push([[key, value], multiplicity]);
55
- __privateGet(this, _indexOut).addValue(key, [value, multiplicity]);
47
+ this.#indexOut.addValue(key, [value, multiplicity]);
56
48
  }
57
49
  }
58
50
  }
@@ -62,7 +54,7 @@ class ReduceOperator extends UnaryOperator {
62
54
  const delta = newMultiplicity - oldMultiplicity;
63
55
  if (delta !== 0) {
64
56
  result.push([[key, value], delta]);
65
- __privateGet(this, _indexOut).addValue(key, [value, delta]);
57
+ this.#indexOut.addValue(key, [value, delta]);
66
58
  }
67
59
  }
68
60
  }
@@ -72,9 +64,6 @@ class ReduceOperator extends UnaryOperator {
72
64
  }
73
65
  }
74
66
  }
75
- _index = new WeakMap();
76
- _indexOut = new WeakMap();
77
- _f = new WeakMap();
78
67
  function reduce(f) {
79
68
  return (stream) => {
80
69
  const output = new StreamBuilder(
@@ -1 +1 @@
1
- {"version":3,"file":"reduce.js","sources":["../../../src/operators/reduce.ts"],"sourcesContent":["import { DifferenceStreamWriter, UnaryOperator } from \"../graph.js\"\nimport { StreamBuilder } from \"../d2.js\"\nimport { MultiSet } from \"../multiset.js\"\nimport { Index } from \"../indexes.js\"\nimport type { DifferenceStreamReader } from \"../graph.js\"\nimport type { IStreamBuilder, KeyValue } from \"../types.js\"\n\n/**\n * Base operator for reduction operations (version-free)\n */\nexport class ReduceOperator<K, V1, V2> extends UnaryOperator<[K, V1], [K, V2]> {\n #index = new Index<K, V1>()\n #indexOut = new Index<K, V2>()\n #f: (values: Array<[V1, number]>) => Array<[V2, number]>\n\n constructor(\n id: number,\n inputA: DifferenceStreamReader<[K, V1]>,\n output: DifferenceStreamWriter<[K, V2]>,\n f: (values: Array<[V1, number]>) => Array<[V2, number]>\n ) {\n super(id, inputA, output)\n this.#f = f\n }\n\n run(): void {\n // Collect all input messages and update the index\n const keysTodo = new Set<K>()\n for (const message of this.inputMessages()) {\n for (const [item, multiplicity] of message.getInner()) {\n const [key, value] = item\n this.#index.addValue(key, [value, multiplicity])\n keysTodo.add(key)\n }\n }\n\n // For each key, compute the reduction and delta\n const result: Array<[[K, V2], number]> = []\n for (const key of keysTodo) {\n const curr = this.#index.get(key)\n const currOut = this.#indexOut.get(key)\n const out = this.#f(curr)\n\n // Create maps for current and previous outputs using values directly as keys\n const newOutputMap = new Map<V2, number>()\n const oldOutputMap = new Map<V2, number>()\n\n // Process new output\n for (const [value, multiplicity] of out) {\n const existing = newOutputMap.get(value) ?? 0\n newOutputMap.set(value, existing + multiplicity)\n }\n\n // Process previous output\n for (const [value, multiplicity] of currOut) {\n const existing = oldOutputMap.get(value) ?? 0\n oldOutputMap.set(value, existing + multiplicity)\n }\n\n // First, emit removals for old values that are no longer present\n for (const [value, multiplicity] of oldOutputMap) {\n if (!newOutputMap.has(value)) {\n // Remove the old value entirely\n result.push([[key, value], -multiplicity])\n this.#indexOut.addValue(key, [value, -multiplicity])\n }\n }\n\n // Then, emit additions for new values that are not present in old\n for (const [value, multiplicity] of newOutputMap) {\n if (!oldOutputMap.has(value)) {\n // Add the new value only if it has non-zero multiplicity\n if (multiplicity !== 0) {\n result.push([[key, value], multiplicity])\n this.#indexOut.addValue(key, [value, multiplicity])\n }\n }\n }\n\n // Finally, emit multiplicity changes for values that were present and are still present\n for (const [value, newMultiplicity] of newOutputMap) {\n const oldMultiplicity = oldOutputMap.get(value)\n if (oldMultiplicity !== undefined) {\n const delta = newMultiplicity - oldMultiplicity\n // Only emit actual changes, i.e. non-zero deltas\n if (delta !== 0) {\n result.push([[key, value], delta])\n this.#indexOut.addValue(key, [value, delta])\n }\n }\n }\n }\n\n if (result.length > 0) {\n this.output.sendData(new MultiSet(result))\n }\n }\n}\n\n/**\n * Reduces the elements in the stream by key (version-free)\n */\nexport function reduce<\n KType extends T extends KeyValue<infer K, infer _V> ? K : never,\n V1Type extends T extends KeyValue<KType, infer V> ? V : never,\n R,\n T,\n>(f: (values: Array<[V1Type, number]>) => Array<[R, number]>) {\n return (stream: IStreamBuilder<T>): IStreamBuilder<KeyValue<KType, R>> => {\n const output = new StreamBuilder<KeyValue<KType, R>>(\n stream.graph,\n new DifferenceStreamWriter<KeyValue<KType, R>>()\n )\n const operator = new ReduceOperator<KType, V1Type, R>(\n stream.graph.getNextOperatorId(),\n stream.connectReader() as DifferenceStreamReader<KeyValue<KType, V1Type>>,\n output.writer,\n f\n )\n stream.graph.addOperator(operator)\n return output\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;;;AAUO,MAAM,uBAAkC,cAAgC;AAAA,EAK7E,YACE,IACA,QACA,QACA,GACA;AACA,UAAM,IAAI,QAAQ,MAAM;AAV1B,+BAAS,IAAI,MAAA;AACb,kCAAY,IAAI,MAAA;AAChB;AASE,uBAAK,IAAK;AAAA,EACZ;AAAA,EAEA,MAAY;AAEV,UAAM,+BAAe,IAAA;AACrB,eAAW,WAAW,KAAK,iBAAiB;AAC1C,iBAAW,CAAC,MAAM,YAAY,KAAK,QAAQ,YAAY;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9C,YAAI,oBAAoB,QAAW;AACjC,gBAAM,QAAQ,kBAAkB;AAEhC,cAAI,UAAU,GAAG;AACf,mBAAO,KAAK,CAAC,CAAC,KAAK,KAAK,GAAG,KAAK,CAAC;AACjC,+BAAK,WAAU,SAAS,KAAK,CAAC,OAAO,KAAK,CAAC;AAAA,UAC7C;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAEA,QAAI,OAAO,SAAS,GAAG;AACrB,WAAK,OAAO,SAAS,IAAI,SAAS,MAAM,CAAC;AAAA,IAC3C;AAAA,EACF;AACF;AAtFE;AACA;AACA;AAyFK,SAAS,OAKd,GAA4D;AAC5D,SAAO,CAAC,WAAkE;AACxE,UAAM,SAAS,IAAI;AAAA,MACjB,OAAO;AAAA,MACP,IAAI,uBAAA;AAAA,IAA2C;AAEjD,UAAM,WAAW,IAAI;AAAA,MACnB,OAAO,MAAM,kBAAA;AAAA,MACb,OAAO,cAAA;AAAA,MACP,OAAO;AAAA,MACP;AAAA,IAAA;AAEF,WAAO,MAAM,YAAY,QAAQ;AACjC,WAAO;AAAA,EACT;AACF;"}
1
+ {"version":3,"file":"reduce.js","sources":["../../../src/operators/reduce.ts"],"sourcesContent":["import { DifferenceStreamWriter, UnaryOperator } from \"../graph.js\"\nimport { StreamBuilder } from \"../d2.js\"\nimport { MultiSet } from \"../multiset.js\"\nimport { Index } from \"../indexes.js\"\nimport type { DifferenceStreamReader } from \"../graph.js\"\nimport type { IStreamBuilder, KeyValue } from \"../types.js\"\n\n/**\n * Base operator for reduction operations (version-free)\n */\nexport class ReduceOperator<K, V1, V2> extends UnaryOperator<[K, V1], [K, V2]> {\n #index = new Index<K, V1>()\n #indexOut = new Index<K, V2>()\n #f: (values: Array<[V1, number]>) => Array<[V2, number]>\n\n constructor(\n id: number,\n inputA: DifferenceStreamReader<[K, V1]>,\n output: DifferenceStreamWriter<[K, V2]>,\n f: (values: Array<[V1, number]>) => Array<[V2, number]>\n ) {\n super(id, inputA, output)\n this.#f = f\n }\n\n run(): void {\n // Collect all input messages and update the index\n const keysTodo = new Set<K>()\n for (const message of this.inputMessages()) {\n for (const [item, multiplicity] of message.getInner()) {\n const [key, value] = item\n this.#index.addValue(key, [value, multiplicity])\n keysTodo.add(key)\n }\n }\n\n // For each key, compute the reduction and delta\n const result: Array<[[K, V2], number]> = []\n for (const key of keysTodo) {\n const curr = this.#index.get(key)\n const currOut = this.#indexOut.get(key)\n const out = this.#f(curr)\n\n // Create maps for current and previous outputs using values directly as keys\n const newOutputMap = new Map<V2, number>()\n const oldOutputMap = new Map<V2, number>()\n\n // Process new output\n for (const [value, multiplicity] of out) {\n const existing = newOutputMap.get(value) ?? 0\n newOutputMap.set(value, existing + multiplicity)\n }\n\n // Process previous output\n for (const [value, multiplicity] of currOut) {\n const existing = oldOutputMap.get(value) ?? 0\n oldOutputMap.set(value, existing + multiplicity)\n }\n\n // First, emit removals for old values that are no longer present\n for (const [value, multiplicity] of oldOutputMap) {\n if (!newOutputMap.has(value)) {\n // Remove the old value entirely\n result.push([[key, value], -multiplicity])\n this.#indexOut.addValue(key, [value, -multiplicity])\n }\n }\n\n // Then, emit additions for new values that are not present in old\n for (const [value, multiplicity] of newOutputMap) {\n if (!oldOutputMap.has(value)) {\n // Add the new value only if it has non-zero multiplicity\n if (multiplicity !== 0) {\n result.push([[key, value], multiplicity])\n this.#indexOut.addValue(key, [value, multiplicity])\n }\n }\n }\n\n // Finally, emit multiplicity changes for values that were present and are still present\n for (const [value, newMultiplicity] of newOutputMap) {\n const oldMultiplicity = oldOutputMap.get(value)\n if (oldMultiplicity !== undefined) {\n const delta = newMultiplicity - oldMultiplicity\n // Only emit actual changes, i.e. non-zero deltas\n if (delta !== 0) {\n result.push([[key, value], delta])\n this.#indexOut.addValue(key, [value, delta])\n }\n }\n }\n }\n\n if (result.length > 0) {\n this.output.sendData(new MultiSet(result))\n }\n }\n}\n\n/**\n * Reduces the elements in the stream by key (version-free)\n */\nexport function reduce<\n KType extends T extends KeyValue<infer K, infer _V> ? K : never,\n V1Type extends T extends KeyValue<KType, infer V> ? V : never,\n R,\n T,\n>(f: (values: Array<[V1Type, number]>) => Array<[R, number]>) {\n return (stream: IStreamBuilder<T>): IStreamBuilder<KeyValue<KType, R>> => {\n const output = new StreamBuilder<KeyValue<KType, R>>(\n stream.graph,\n new DifferenceStreamWriter<KeyValue<KType, R>>()\n )\n const operator = new ReduceOperator<KType, V1Type, R>(\n stream.graph.getNextOperatorId(),\n stream.connectReader() as DifferenceStreamReader<KeyValue<KType, V1Type>>,\n output.writer,\n f\n )\n stream.graph.addOperator(operator)\n return output\n }\n}\n"],"names":[],"mappings":";;;;AAUO,MAAM,uBAAkC,cAAgC;AAAA,EAC7E,SAAS,IAAI,MAAA;AAAA,EACb,YAAY,IAAI,MAAA;AAAA,EAChB;AAAA,EAEA,YACE,IACA,QACA,QACA,GACA;AACA,UAAM,IAAI,QAAQ,MAAM;AACxB,SAAK,KAAK;AAAA,EACZ;AAAA,EAEA,MAAY;AAEV,UAAM,+BAAe,IAAA;AACrB,eAAW,WAAW,KAAK,iBAAiB;AAC1C,iBAAW,CAAC,MAAM,YAAY,KAAK,QAAQ,YAAY;AACrD,cAAM,CAAC,KAAK,KAAK,IAAI;AACrB,aAAK,OAAO,SAAS,KAAK,CAAC,OAAO,YAAY,CAAC;AAC/C,iBAAS,IAAI,GAAG;AAAA,MAClB;AAAA,IACF;AAGA,UAAM,SAAmC,CAAA;AACzC,eAAW,OAAO,UAAU;AAC1B,YAAM,OAAO,KAAK,OAAO,IAAI,GAAG;AAChC,YAAM,UAAU,KAAK,UAAU,IAAI,GAAG;AACtC,YAAM,MAAM,KAAK,GAAG,IAAI;AAGxB,YAAM,mCAAmB,IAAA;AACzB,YAAM,mCAAmB,IAAA;AAGzB,iBAAW,CAAC,OAAO,YAAY,KAAK,KAAK;AACvC,cAAM,WAAW,aAAa,IAAI,KAAK,KAAK;AAC5C,qBAAa,IAAI,OAAO,WAAW,YAAY;AAAA,MACjD;AAGA,iBAAW,CAAC,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BAAA;AAAA,MACb,OAAO,cAAA;AAAA,MACP,OAAO;AAAA,MACP;AAAA,IAAA;AAEF,WAAO,MAAM,YAAY,QAAQ;AACjC,WAAO;AAAA,EACT;AACF;"}
@@ -1,25 +1,16 @@
1
- var __typeError = (msg) => {
2
- throw TypeError(msg);
3
- };
4
- var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
5
- var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
6
- var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
7
- var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
8
- var _f;
9
1
  import { LinearUnaryOperator, DifferenceStreamWriter } from "../graph.js";
10
2
  import { StreamBuilder } from "../d2.js";
11
3
  class TapOperator extends LinearUnaryOperator {
4
+ #f;
12
5
  constructor(id, inputA, output, f) {
13
6
  super(id, inputA, output);
14
- __privateAdd(this, _f);
15
- __privateSet(this, _f, f);
7
+ this.#f = f;
16
8
  }
17
9
  inner(collection) {
18
- __privateGet(this, _f).call(this, collection);
10
+ this.#f(collection);
19
11
  return collection;
20
12
  }
21
13
  }
22
- _f = new WeakMap();
23
14
  function tap(f) {
24
15
  return (stream) => {
25
16
  const output = new StreamBuilder(
@@ -1 +1 @@
1
- {"version":3,"file":"tap.js","sources":["../../../src/operators/tap.ts"],"sourcesContent":["import { DifferenceStreamWriter, LinearUnaryOperator } from \"../graph.js\"\nimport { StreamBuilder } from \"../d2.js\"\nimport type { IStreamBuilder, PipedOperator } from \"../types.js\"\nimport type { DifferenceStreamReader } from \"../graph.js\"\nimport type { MultiSet } from \"../multiset.js\"\n\n/**\n * Operator that applies a function to each multi-set in the input stream\n */\nexport class TapOperator<T> extends LinearUnaryOperator<T, T> {\n #f: (data: MultiSet<T>) => void\n\n constructor(\n id: number,\n inputA: DifferenceStreamReader<T>,\n output: DifferenceStreamWriter<T>,\n f: (data: MultiSet<T>) => void\n ) {\n super(id, inputA, output)\n this.#f = f\n }\n\n inner(collection: MultiSet<T>): MultiSet<T> {\n this.#f(collection)\n return collection\n }\n}\n\n/**\n * Invokes a function for each multi-set in the input stream.\n * This operator doesn't modify the stream and is used to perform side effects.\n * @param f - The function to invoke on each multi-set\n * @returns The input stream\n */\nexport function tap<T>(f: (data: MultiSet<T>) => void): PipedOperator<T, T> {\n return (stream: IStreamBuilder<T>): IStreamBuilder<T> => {\n const output = new StreamBuilder<T>(\n stream.graph,\n new DifferenceStreamWriter<T>()\n )\n const operator = new TapOperator<T>(\n stream.graph.getNextOperatorId(),\n stream.connectReader(),\n output.writer,\n f\n )\n stream.graph.addOperator(operator)\n return output\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;AASO,MAAM,oBAAuB,oBAA0B;AAAA,EAG5D,YACE,IACA,QACA,QACA,GACA;AACA,UAAM,IAAI,QAAQ,MAAM;AAR1B;AASE,uBAAK,IAAK;AAAA,EACZ;AAAA,EAEA,MAAM,YAAsC;AAC1C,uBAAK,IAAL,WAAQ;AACR,WAAO;AAAA,EACT;AACF;AAhBE;AAwBK,SAAS,IAAO,GAAqD;AAC1E,SAAO,CAAC,WAAiD;AACvD,UAAM,SAAS,IAAI;AAAA,MACjB,OAAO;AAAA,MACP,IAAI,uBAAA;AAAA,IAA0B;AAEhC,UAAM,WAAW,IAAI;AAAA,MACnB,OAAO,MAAM,kBAAA;AAAA,MACb,OAAO,cAAA;AAAA,MACP,OAAO;AAAA,MACP;AAAA,IAAA;AAEF,WAAO,MAAM,YAAY,QAAQ;AACjC,WAAO;AAAA,EACT;AACF;"}
1
+ {"version":3,"file":"tap.js","sources":["../../../src/operators/tap.ts"],"sourcesContent":["import { DifferenceStreamWriter, LinearUnaryOperator } from \"../graph.js\"\nimport { StreamBuilder } from \"../d2.js\"\nimport type { IStreamBuilder, PipedOperator } from \"../types.js\"\nimport type { DifferenceStreamReader } from \"../graph.js\"\nimport type { MultiSet } from \"../multiset.js\"\n\n/**\n * Operator that applies a function to each multi-set in the input stream\n */\nexport class TapOperator<T> extends LinearUnaryOperator<T, T> {\n #f: (data: MultiSet<T>) => void\n\n constructor(\n id: number,\n inputA: DifferenceStreamReader<T>,\n output: DifferenceStreamWriter<T>,\n f: (data: MultiSet<T>) => void\n ) {\n super(id, inputA, output)\n this.#f = f\n }\n\n inner(collection: MultiSet<T>): MultiSet<T> {\n this.#f(collection)\n return collection\n }\n}\n\n/**\n * Invokes a function for each multi-set in the input stream.\n * This operator doesn't modify the stream and is used to perform side effects.\n * @param f - The function to invoke on each multi-set\n * @returns The input stream\n */\nexport function tap<T>(f: (data: MultiSet<T>) => void): PipedOperator<T, T> {\n return (stream: IStreamBuilder<T>): IStreamBuilder<T> => {\n const output = new StreamBuilder<T>(\n stream.graph,\n new DifferenceStreamWriter<T>()\n )\n const operator = new TapOperator<T>(\n stream.graph.getNextOperatorId(),\n stream.connectReader(),\n output.writer,\n f\n )\n stream.graph.addOperator(operator)\n return output\n }\n}\n"],"names":[],"mappings":";;AASO,MAAM,oBAAuB,oBAA0B;AAAA,EAC5D;AAAA,EAEA,YACE,IACA,QACA,QACA,GACA;AACA,UAAM,IAAI,QAAQ,MAAM;AACxB,SAAK,KAAK;AAAA,EACZ;AAAA,EAEA,MAAM,YAAsC;AAC1C,SAAK,GAAG,UAAU;AAClB,WAAO;AAAA,EACT;AACF;AAQO,SAAS,IAAO,GAAqD;AAC1E,SAAO,CAAC,WAAiD;AACvD,UAAM,SAAS,IAAI;AAAA,MACjB,OAAO;AAAA,MACP,IAAI,uBAAA;AAAA,IAA0B;AAEhC,UAAM,WAAW,IAAI;AAAA,MACnB,OAAO,MAAM,kBAAA;AAAA,MACb,OAAO,cAAA;AAAA,MACP,OAAO;AAAA,MACP;AAAA,IAAA;AAEF,WAAO,MAAM,YAAY,QAAQ;AACjC,WAAO;AAAA,EACT;AACF;"}
@@ -1,5 +1,4 @@
1
- import { PipedOperator } from '../types.js';
2
- import { KeyValue } from '../types.js';
1
+ import { KeyValue, PipedOperator } from '../types.js';
3
2
  interface TopKOptions {
4
3
  limit?: number;
5
4
  offset?: number;
@@ -1,8 +1,8 @@
1
1
  import { MultiSet } from "../multiset.js";
2
2
  import { reduce } from "./reduce.js";
3
3
  function topK(comparator, options) {
4
- const limit = (options == null ? void 0 : options.limit) ?? Infinity;
5
- const offset = (options == null ? void 0 : options.offset) ?? 0;
4
+ const limit = options?.limit ?? Infinity;
5
+ const offset = options?.offset ?? 0;
6
6
  return (stream) => {
7
7
  const reduced = stream.pipe(
8
8
  reduce((values) => {
@@ -15,8 +15,8 @@ function topK(comparator, options) {
15
15
  };
16
16
  }
17
17
  function topKWithIndex(comparator, options) {
18
- const limit = (options == null ? void 0 : options.limit) ?? Infinity;
19
- const offset = (options == null ? void 0 : options.offset) ?? 0;
18
+ const limit = options?.limit ?? Infinity;
19
+ const offset = options?.offset ?? 0;
20
20
  return (stream) => {
21
21
  const reduced = stream.pipe(
22
22
  reduce((values) => {
@@ -1 +1 @@
1
- {"version":3,"file":"topK.js","sources":["../../../src/operators/topK.ts"],"sourcesContent":["import { MultiSet } from \"../multiset.js\"\nimport { reduce } from \"./reduce.js\"\nimport type { IStreamBuilder, PipedOperator } from \"../types\"\nimport type { KeyValue } from \"../types.js\"\n\ninterface TopKOptions {\n limit?: number\n offset?: number\n}\n\n/**\n * Limits the number of results based on a comparator, with optional offset.\n * This works on a keyed stream, where the key is the first element of the tuple\n * The ordering is withing a key group, i.e. elements are sorted within a key group\n * and the limit + offset is applied to that sorted group.\n * To order the entire stream, key by the same value for all elements such as null.\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 limits the number of results\n */\nexport function topK<\n KType extends T extends KeyValue<infer K, infer _V> ? K : never,\n V1Type extends T extends KeyValue<KType, infer V> ? V : never,\n T,\n>(\n comparator: (a: V1Type, b: V1Type) => number,\n options?: TopKOptions\n): PipedOperator<T, T> {\n const limit = options?.limit ?? Infinity\n const offset = options?.offset ?? 0\n\n return (stream: IStreamBuilder<T>): IStreamBuilder<T> => {\n const reduced = stream.pipe(\n reduce((values) => {\n // `values` is a list of tuples, first element is the value, second is the multiplicity\n const consolidated = new MultiSet(values).consolidate()\n const sortedValues = consolidated\n .getInner()\n .sort((a, b) => comparator(a[0] as V1Type, b[0] as V1Type))\n return sortedValues.slice(offset, offset + limit)\n })\n )\n return reduced as IStreamBuilder<T>\n }\n}\n\n/**\n * Limits the number of results based on a comparator, with optional offset.\n * This works on a keyed stream, where the key is the first element of the tuple\n * The ordering is withing a key group, i.e. elements are sorted within a key group\n * and the limit + offset is applied to that sorted group.\n * To order the entire stream, key by the same value for all elements such as null.\n * Adds the index of the element to the result as [key, [value, index]]\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 topKWithIndex<\n KType extends T extends KeyValue<infer K, infer _V> ? K : never,\n V1Type extends T extends KeyValue<KType, infer V> ? V : never,\n T,\n>(\n comparator: (a: V1Type, b: V1Type) => number,\n options?: TopKOptions\n): PipedOperator<T, KeyValue<KType, [V1Type, number]>> {\n const limit = options?.limit ?? Infinity\n const offset = options?.offset ?? 0\n\n return (\n stream: IStreamBuilder<T>\n ): IStreamBuilder<KeyValue<KType, [V1Type, number]>> => {\n const reduced = stream.pipe(\n reduce<KType, V1Type, [V1Type, number], T>((values) => {\n // `values` is a list of tuples, first element is the value, second is the multiplicity\n const consolidated = new MultiSet(values).consolidate()\n let i = offset\n const sortedValues = consolidated\n .getInner()\n .sort((a, b) => comparator(a[0], b[0]))\n .slice(offset, offset + limit)\n .map(([value, multiplicity]): [[V1Type, number], number] => [\n [value, i++],\n multiplicity,\n ])\n return sortedValues\n })\n )\n return reduced\n }\n}\n"],"names":[],"mappings":";;AAqBO,SAAS,KAKd,YACA,SACqB;AACrB,QAAM,SAAQ,mCAAS,UAAS;AAChC,QAAM,UAAS,mCAAS,WAAU;AAElC,SAAO,CAAC,WAAiD;AACvD,UAAM,UAAU,OAAO;AAAA,MACrB,OAAO,CAAC,WAAW;AAEjB,cAAM,eAAe,IAAI,SAAS,MAAM,EAAE,YAAA;AAC1C,cAAM,eAAe,aAClB,SAAA,EACA,KAAK,CAAC,GAAG,MAAM,WAAW,EAAE,CAAC,GAAa,EAAE,CAAC,CAAW,CAAC;AAC5D,eAAO,aAAa,MAAM,QAAQ,SAAS,KAAK;AAAA,MAClD,CAAC;AAAA,IAAA;AAEH,WAAO;AAAA,EACT;AACF;AAcO,SAAS,cAKd,YACA,SACqD;AACrD,QAAM,SAAQ,mCAAS,UAAS;AAChC,QAAM,UAAS,mCAAS,WAAU;AAElC,SAAO,CACL,WACsD;AACtD,UAAM,UAAU,OAAO;AAAA,MACrB,OAA2C,CAAC,WAAW;AAErD,cAAM,eAAe,IAAI,SAAS,MAAM,EAAE,YAAA;AAC1C,YAAI,IAAI;AACR,cAAM,eAAe,aAClB,SAAA,EACA,KAAK,CAAC,GAAG,MAAM,WAAW,EAAE,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,EACrC,MAAM,QAAQ,SAAS,KAAK,EAC5B,IAAI,CAAC,CAAC,OAAO,YAAY,MAAkC;AAAA,UAC1D,CAAC,OAAO,GAAG;AAAA,UACX;AAAA,QAAA,CACD;AACH,eAAO;AAAA,MACT,CAAC;AAAA,IAAA;AAEH,WAAO;AAAA,EACT;AACF;"}
1
+ {"version":3,"file":"topK.js","sources":["../../../src/operators/topK.ts"],"sourcesContent":["import { MultiSet } from \"../multiset.js\"\nimport { reduce } from \"./reduce.js\"\nimport type { IStreamBuilder, KeyValue, PipedOperator } from \"../types\"\n\ninterface TopKOptions {\n limit?: number\n offset?: number\n}\n\n/**\n * Limits the number of results based on a comparator, with optional offset.\n * This works on a keyed stream, where the key is the first element of the tuple\n * The ordering is withing a key group, i.e. elements are sorted within a key group\n * and the limit + offset is applied to that sorted group.\n * To order the entire stream, key by the same value for all elements such as null.\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 limits the number of results\n */\nexport function topK<\n KType extends T extends KeyValue<infer K, infer _V> ? K : never,\n V1Type extends T extends KeyValue<KType, infer V> ? V : never,\n T,\n>(\n comparator: (a: V1Type, b: V1Type) => number,\n options?: TopKOptions\n): PipedOperator<T, T> {\n const limit = options?.limit ?? Infinity\n const offset = options?.offset ?? 0\n\n return (stream: IStreamBuilder<T>): IStreamBuilder<T> => {\n const reduced = stream.pipe(\n reduce((values) => {\n // `values` is a list of tuples, first element is the value, second is the multiplicity\n const consolidated = new MultiSet(values).consolidate()\n const sortedValues = consolidated\n .getInner()\n .sort((a, b) => comparator(a[0] as V1Type, b[0] as V1Type))\n return sortedValues.slice(offset, offset + limit)\n })\n )\n return reduced as IStreamBuilder<T>\n }\n}\n\n/**\n * Limits the number of results based on a comparator, with optional offset.\n * This works on a keyed stream, where the key is the first element of the tuple\n * The ordering is withing a key group, i.e. elements are sorted within a key group\n * and the limit + offset is applied to that sorted group.\n * To order the entire stream, key by the same value for all elements such as null.\n * Adds the index of the element to the result as [key, [value, index]]\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 topKWithIndex<\n KType extends T extends KeyValue<infer K, infer _V> ? K : never,\n V1Type extends T extends KeyValue<KType, infer V> ? V : never,\n T,\n>(\n comparator: (a: V1Type, b: V1Type) => number,\n options?: TopKOptions\n): PipedOperator<T, KeyValue<KType, [V1Type, number]>> {\n const limit = options?.limit ?? Infinity\n const offset = options?.offset ?? 0\n\n return (\n stream: IStreamBuilder<T>\n ): IStreamBuilder<KeyValue<KType, [V1Type, number]>> => {\n const reduced = stream.pipe(\n reduce<KType, V1Type, [V1Type, number], T>((values) => {\n // `values` is a list of tuples, first element is the value, second is the multiplicity\n const consolidated = new MultiSet(values).consolidate()\n let i = offset\n const sortedValues = consolidated\n .getInner()\n .sort((a, b) => comparator(a[0], b[0]))\n .slice(offset, offset + limit)\n .map(([value, multiplicity]): [[V1Type, number], number] => [\n [value, i++],\n multiplicity,\n ])\n return sortedValues\n })\n )\n return reduced\n }\n}\n"],"names":[],"mappings":";;AAoBO,SAAS,KAKd,YACA,SACqB;AACrB,QAAM,QAAQ,SAAS,SAAS;AAChC,QAAM,SAAS,SAAS,UAAU;AAElC,SAAO,CAAC,WAAiD;AACvD,UAAM,UAAU,OAAO;AAAA,MACrB,OAAO,CAAC,WAAW;AAEjB,cAAM,eAAe,IAAI,SAAS,MAAM,EAAE,YAAA;AAC1C,cAAM,eAAe,aAClB,SAAA,EACA,KAAK,CAAC,GAAG,MAAM,WAAW,EAAE,CAAC,GAAa,EAAE,CAAC,CAAW,CAAC;AAC5D,eAAO,aAAa,MAAM,QAAQ,SAAS,KAAK;AAAA,MAClD,CAAC;AAAA,IAAA;AAEH,WAAO;AAAA,EACT;AACF;AAcO,SAAS,cAKd,YACA,SACqD;AACrD,QAAM,QAAQ,SAAS,SAAS;AAChC,QAAM,SAAS,SAAS,UAAU;AAElC,SAAO,CACL,WACsD;AACtD,UAAM,UAAU,OAAO;AAAA,MACrB,OAA2C,CAAC,WAAW;AAErD,cAAM,eAAe,IAAI,SAAS,MAAM,EAAE,YAAA;AAC1C,YAAI,IAAI;AACR,cAAM,eAAe,aAClB,SAAA,EACA,KAAK,CAAC,GAAG,MAAM,WAAW,EAAE,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,EACrC,MAAM,QAAQ,SAAS,KAAK,EAC5B,IAAI,CAAC,CAAC,OAAO,YAAY,MAAkC;AAAA,UAC1D,CAAC,OAAO,GAAG;AAAA,UACX;AAAA,QAAA,CACD;AACH,eAAO;AAAA,MACT,CAAC;AAAA,IAAA;AAEH,WAAO;AAAA,EACT;AACF;"}
@@ -1,48 +1,38 @@
1
- var __typeError = (msg) => {
2
- throw TypeError(msg);
3
- };
4
- var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
5
- var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
6
- var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
7
- var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
8
- var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
9
- var _sortedValues, _comparator, _topKStart, _topKEnd, _TopKArray_instances, findIndex_fn, _index, _topK, _limit;
10
1
  import { generateKeyBetween } from "fractional-indexing";
11
2
  import { UnaryOperator, DifferenceStreamWriter } from "../graph.js";
12
3
  import { StreamBuilder } from "../d2.js";
13
4
  import { MultiSet } from "../multiset.js";
14
5
  import { binarySearch, globalObjectIdGenerator } from "../utils.js";
15
6
  class TopKArray {
7
+ #sortedValues = [];
8
+ #comparator;
9
+ #topKStart;
10
+ #topKEnd;
16
11
  constructor(offset, limit, comparator) {
17
- __privateAdd(this, _TopKArray_instances);
18
- __privateAdd(this, _sortedValues, []);
19
- __privateAdd(this, _comparator);
20
- __privateAdd(this, _topKStart);
21
- __privateAdd(this, _topKEnd);
22
- __privateSet(this, _topKStart, offset);
23
- __privateSet(this, _topKEnd, offset + limit);
24
- __privateSet(this, _comparator, comparator);
12
+ this.#topKStart = offset;
13
+ this.#topKEnd = offset + limit;
14
+ this.#comparator = comparator;
25
15
  }
26
16
  get size() {
27
- const offset = __privateGet(this, _topKStart);
28
- const limit = __privateGet(this, _topKEnd) - __privateGet(this, _topKStart);
29
- const available = __privateGet(this, _sortedValues).length - offset;
17
+ const offset = this.#topKStart;
18
+ const limit = this.#topKEnd - this.#topKStart;
19
+ const available = this.#sortedValues.length - offset;
30
20
  return Math.max(0, Math.min(limit, available));
31
21
  }
32
22
  insert(value) {
33
23
  const result = { moveIn: null, moveOut: null };
34
- const index = __privateMethod(this, _TopKArray_instances, findIndex_fn).call(this, value);
35
- const indexBefore = index === 0 ? null : getIndex(__privateGet(this, _sortedValues)[index - 1]);
36
- const indexAfter = index === __privateGet(this, _sortedValues).length ? null : getIndex(__privateGet(this, _sortedValues)[index]);
24
+ const index = this.#findIndex(value);
25
+ const indexBefore = index === 0 ? null : getIndex(this.#sortedValues[index - 1]);
26
+ const indexAfter = index === this.#sortedValues.length ? null : getIndex(this.#sortedValues[index]);
37
27
  const fractionalIndex = generateKeyBetween(indexBefore, indexAfter);
38
28
  const val = indexedValue(value, fractionalIndex);
39
- __privateGet(this, _sortedValues).splice(index, 0, val);
40
- if (index < __privateGet(this, _topKEnd)) {
41
- const moveInIndex = Math.max(index, __privateGet(this, _topKStart));
42
- if (moveInIndex < __privateGet(this, _sortedValues).length) {
43
- result.moveIn = __privateGet(this, _sortedValues)[moveInIndex];
44
- if (__privateGet(this, _topKEnd) < __privateGet(this, _sortedValues).length) {
45
- result.moveOut = __privateGet(this, _sortedValues)[__privateGet(this, _topKEnd)];
29
+ this.#sortedValues.splice(index, 0, val);
30
+ if (index < this.#topKEnd) {
31
+ const moveInIndex = Math.max(index, this.#topKStart);
32
+ if (moveInIndex < this.#sortedValues.length) {
33
+ result.moveIn = this.#sortedValues[moveInIndex];
34
+ if (this.#topKEnd < this.#sortedValues.length) {
35
+ result.moveOut = this.#sortedValues[this.#topKEnd];
46
36
  }
47
37
  }
48
38
  }
@@ -56,54 +46,48 @@ class TopKArray {
56
46
  */
57
47
  delete(value) {
58
48
  const result = { moveIn: null, moveOut: null };
59
- const index = __privateMethod(this, _TopKArray_instances, findIndex_fn).call(this, value);
60
- const [removedElem] = __privateGet(this, _sortedValues).splice(index, 1);
61
- if (index < __privateGet(this, _topKEnd)) {
49
+ const index = this.#findIndex(value);
50
+ const [removedElem] = this.#sortedValues.splice(index, 1);
51
+ if (index < this.#topKEnd) {
62
52
  result.moveOut = removedElem;
63
- if (index < __privateGet(this, _topKStart)) {
64
- const moveOutIndex = __privateGet(this, _topKStart) - 1;
65
- if (moveOutIndex < __privateGet(this, _sortedValues).length) {
66
- result.moveOut = __privateGet(this, _sortedValues)[moveOutIndex];
53
+ if (index < this.#topKStart) {
54
+ const moveOutIndex = this.#topKStart - 1;
55
+ if (moveOutIndex < this.#sortedValues.length) {
56
+ result.moveOut = this.#sortedValues[moveOutIndex];
67
57
  } else {
68
58
  result.moveOut = null;
69
59
  }
70
60
  }
71
- const moveInIndex = __privateGet(this, _topKEnd) - 1;
72
- if (moveInIndex < __privateGet(this, _sortedValues).length) {
73
- result.moveIn = __privateGet(this, _sortedValues)[moveInIndex];
61
+ const moveInIndex = this.#topKEnd - 1;
62
+ if (moveInIndex < this.#sortedValues.length) {
63
+ result.moveIn = this.#sortedValues[moveInIndex];
74
64
  }
75
65
  }
76
66
  return result;
77
67
  }
68
+ // TODO: see if there is a way to refactor the code for insert and delete in the topK above
69
+ // because they are very similar, one is shifting the topK window to the left and the other is shifting it to the right
70
+ // so i have the feeling there is a common pattern here and we can implement both cases using that pattern
71
+ #findIndex(value) {
72
+ return binarySearch(
73
+ this.#sortedValues,
74
+ indexedValue(value, ``),
75
+ (a, b) => this.#comparator(getValue(a), getValue(b))
76
+ );
77
+ }
78
78
  }
79
- _sortedValues = new WeakMap();
80
- _comparator = new WeakMap();
81
- _topKStart = new WeakMap();
82
- _topKEnd = new WeakMap();
83
- _TopKArray_instances = new WeakSet();
84
- // TODO: see if there is a way to refactor the code for insert and delete in the topK above
85
- // because they are very similar, one is shifting the topK window to the left and the other is shifting it to the right
86
- // so i have the feeling there is a common pattern here and we can implement both cases using that pattern
87
- findIndex_fn = function(value) {
88
- return binarySearch(
89
- __privateGet(this, _sortedValues),
90
- indexedValue(value, ``),
91
- (a, b) => __privateGet(this, _comparator).call(this, getValue(a), getValue(b))
92
- );
93
- };
94
79
  class TopKWithFractionalIndexOperator extends UnaryOperator {
80
+ #index = /* @__PURE__ */ new Map();
81
+ // maps keys to their multiplicity
82
+ /**
83
+ * topK data structure that supports insertions and deletions
84
+ * and returns changes to the topK.
85
+ */
86
+ #topK;
87
+ #limit;
95
88
  constructor(id, inputA, output, comparator, options) {
96
- var _a;
97
89
  super(id, inputA, output);
98
- __privateAdd(this, _index, /* @__PURE__ */ new Map());
99
- // maps keys to their multiplicity
100
- /**
101
- * topK data structure that supports insertions and deletions
102
- * and returns changes to the topK.
103
- */
104
- __privateAdd(this, _topK);
105
- __privateAdd(this, _limit);
106
- __privateSet(this, _limit, options.limit ?? Infinity);
90
+ this.#limit = options.limit ?? Infinity;
107
91
  const offset = options.offset ?? 0;
108
92
  const compareTaggedValues = (a, b) => {
109
93
  const valueComparison = comparator(getVal(a), getVal(b));
@@ -114,8 +98,8 @@ class TopKWithFractionalIndexOperator extends UnaryOperator {
114
98
  const tieBreakerB = getTag(b);
115
99
  return tieBreakerA - tieBreakerB;
116
100
  };
117
- __privateSet(this, _topK, this.createTopK(offset, __privateGet(this, _limit), compareTaggedValues));
118
- (_a = options.setSizeCallback) == null ? void 0 : _a.call(options, () => __privateGet(this, _topK).size);
101
+ this.#topK = this.createTopK(offset, this.#limit, compareTaggedValues);
102
+ options.setSizeCallback?.(() => this.#topK.size);
119
103
  }
120
104
  createTopK(offset, limit, comparator) {
121
105
  return new TopKArray(offset, limit, comparator);
@@ -140,10 +124,10 @@ class TopKWithFractionalIndexOperator extends UnaryOperator {
140
124
  };
141
125
  if (oldMultiplicity <= 0 && newMultiplicity > 0) {
142
126
  const taggedValue = tagValue(key, value);
143
- res = __privateGet(this, _topK).insert(taggedValue);
127
+ res = this.#topK.insert(taggedValue);
144
128
  } else if (oldMultiplicity > 0 && newMultiplicity <= 0) {
145
129
  const taggedValue = tagValue(key, value);
146
- res = __privateGet(this, _topK).delete(taggedValue);
130
+ res = this.#topK.delete(taggedValue);
147
131
  } else ;
148
132
  if (res.moveIn) {
149
133
  const index = getIndex(res.moveIn);
@@ -162,22 +146,19 @@ class TopKWithFractionalIndexOperator extends UnaryOperator {
162
146
  return;
163
147
  }
164
148
  getMultiplicity(key) {
165
- return __privateGet(this, _index).get(key) ?? 0;
149
+ return this.#index.get(key) ?? 0;
166
150
  }
167
151
  addKey(key, multiplicity) {
168
152
  const oldMultiplicity = this.getMultiplicity(key);
169
153
  const newMultiplicity = oldMultiplicity + multiplicity;
170
154
  if (newMultiplicity === 0) {
171
- __privateGet(this, _index).delete(key);
155
+ this.#index.delete(key);
172
156
  } else {
173
- __privateGet(this, _index).set(key, newMultiplicity);
157
+ this.#index.set(key, newMultiplicity);
174
158
  }
175
159
  return { oldMultiplicity, newMultiplicity };
176
160
  }
177
161
  }
178
- _index = new WeakMap();
179
- _topK = new WeakMap();
180
- _limit = new WeakMap();
181
162
  function topKWithFractionalIndex(comparator, options) {
182
163
  const opts = options || {};
183
164
  return (stream) => {
@@ -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 { binarySearch, globalObjectIdGenerator } 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}\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\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 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 #limit: number\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 this.#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, this.#limit, compareTaggedValues)\n options.setSizeCallback?.(() => this.#topK.size)\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 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 if (res.moveIn) {\n const index = getIndex(res.moveIn)\n const taggedValue = getValue(res.moveIn)\n const k = getKey(taggedValue)\n const val = getVal(taggedValue)\n result.push([[k, [val, index]], 1])\n }\n\n if (res.moveOut) {\n const index = getIndex(res.moveOut)\n const taggedValue = getValue(res.moveOut)\n const k = getKey(taggedValue)\n const val = getVal(taggedValue)\n result.push([[k, [val, index]], -1])\n }\n\n return\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":";;;;;;;;;;;;;;AAqCA,MAAM,UAAgC;AAAA,EAMpC,YACE,QACA,OACA,YACA;AAVJ;AACE,sCAAwC,CAAA;AACxC;AACA;AACA;AAOE,uBAAK,YAAa;AAClB,uBAAK,UAAW,SAAS;AACzB,uBAAK,aAAc;AAAA,EACrB;AAAA,EAEA,IAAI,OAAe;AACjB,UAAM,SAAS,mBAAK;AACpB,UAAM,QAAQ,mBAAK,YAAW,mBAAK;AACnC,UAAM,YAAY,mBAAK,eAAc,SAAS;AAC9C,WAAO,KAAK,IAAI,GAAG,KAAK,IAAI,OAAO,SAAS,CAAC;AAAA,EAC/C;AAAA,EAEA,OAAO,OAA0B;AAC/B,UAAM,SAAyB,EAAE,QAAQ,MAAM,SAAS,KAAA;AAGxD,UAAM,QAAQ,sBAAK,oCAAL,WAAgB;AAE9B,UAAM,cACJ,UAAU,IAAI,OAAO,SAAS,mBAAK,eAAc,QAAQ,CAAC,CAAE;AAC9D,UAAM,aACJ,UAAU,mBAAK,eAAc,SACzB,OACA,SAAS,mBAAK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O,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 { generateKeyBetween } from \"fractional-indexing\"\nimport { DifferenceStreamWriter, UnaryOperator } from \"../graph.js\"\nimport { StreamBuilder } from \"../d2.js\"\nimport { MultiSet } from \"../multiset.js\"\nimport { binarySearch, globalObjectIdGenerator } 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}\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\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 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 #limit: number\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 this.#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, this.#limit, compareTaggedValues)\n options.setSizeCallback?.(() => this.#topK.size)\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 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 if (res.moveIn) {\n const index = getIndex(res.moveIn)\n const taggedValue = getValue(res.moveIn)\n const k = getKey(taggedValue)\n const val = getVal(taggedValue)\n result.push([[k, [val, index]], 1])\n }\n\n if (res.moveOut) {\n const index = getIndex(res.moveOut)\n const taggedValue = getValue(res.moveOut)\n const k = getKey(taggedValue)\n const val = getVal(taggedValue)\n result.push([[k, [val, index]], -1])\n }\n\n return\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":";;;;;AAqCA,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;AAA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AO,OAAO,GAAG;AAAA,IACxB,OAAO;AACL,WAAK,OAAO,IAAI,KAAK,eAAe;AAAA,IACtC;AACA,WAAO,EAAE,iBAAiB,gBAAA;AAAA,EAC5B;AACF;AAYO,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;"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@tanstack/db-ivm",
3
3
  "description": "Incremental View Maintenance for TanStack DB based on Differential Dataflow",
4
- "version": "0.1.9",
4
+ "version": "0.1.10",
5
5
  "dependencies": {
6
6
  "fractional-indexing": "^3.2.0",
7
7
  "sorted-btree": "^1.8.1"
package/src/indexes.ts CHANGED
@@ -150,11 +150,30 @@ export class Index<TKey, TValue, TPrefix = any> {
150
150
  * hash to identify identical values, storing them in a third level value map.
151
151
  */
152
152
  #inner: IndexMap<TKey, TValue, TPrefix>
153
+ #consolidatedMultiplicity: Map<TKey, number> = new Map() // sum of multiplicities per key
153
154
 
154
155
  constructor() {
155
156
  this.#inner = new Map()
156
157
  }
157
158
 
159
+ /**
160
+ * Create an Index from multiple MultiSet messages.
161
+ * @param messages - Array of MultiSet messages to build the index from.
162
+ * @returns A new Index containing all the data from the messages.
163
+ */
164
+ static fromMultiSets<K, V>(messages: Array<MultiSet<[K, V]>>): Index<K, V> {
165
+ const index = new Index<K, V>()
166
+
167
+ for (const message of messages) {
168
+ for (const [item, multiplicity] of message.getInner()) {
169
+ const [key, value] = item
170
+ index.addValue(key, [value, multiplicity])
171
+ }
172
+ }
173
+
174
+ return index
175
+ }
176
+
158
177
  /**
159
178
  * This method returns a string representation of the index.
160
179
  * @param indent - Whether to indent the string representation.
@@ -184,6 +203,32 @@ export class Index<TKey, TValue, TPrefix = any> {
184
203
  return this.#inner.has(key)
185
204
  }
186
205
 
206
+ /**
207
+ * Check if a key has presence (non-zero consolidated multiplicity).
208
+ * @param key - The key to check.
209
+ * @returns True if the key has non-zero consolidated multiplicity, false otherwise.
210
+ */
211
+ hasPresence(key: TKey): boolean {
212
+ return (this.#consolidatedMultiplicity.get(key) || 0) !== 0
213
+ }
214
+
215
+ /**
216
+ * Get the consolidated multiplicity (sum of multiplicities) for a key.
217
+ * @param key - The key to get the consolidated multiplicity for.
218
+ * @returns The consolidated multiplicity for the key.
219
+ */
220
+ getConsolidatedMultiplicity(key: TKey): number {
221
+ return this.#consolidatedMultiplicity.get(key) || 0
222
+ }
223
+
224
+ /**
225
+ * Get all keys that have presence (non-zero consolidated multiplicity).
226
+ * @returns An iterator of keys with non-zero consolidated multiplicity.
227
+ */
228
+ getPresenceKeys(): Iterable<TKey> {
229
+ return this.#consolidatedMultiplicity.keys()
230
+ }
231
+
187
232
  /**
188
233
  * This method returns all values for a given key.
189
234
  * @param key - The key to get the values for.
@@ -257,6 +302,15 @@ export class Index<TKey, TValue, TPrefix = any> {
257
302
  // If the multiplicity is 0, do nothing
258
303
  if (multiplicity === 0) return
259
304
 
305
+ // Update consolidated multiplicity tracking
306
+ const newConsolidatedMultiplicity =
307
+ (this.#consolidatedMultiplicity.get(key) || 0) + multiplicity
308
+ if (newConsolidatedMultiplicity === 0) {
309
+ this.#consolidatedMultiplicity.delete(key)
310
+ } else {
311
+ this.#consolidatedMultiplicity.set(key, newConsolidatedMultiplicity)
312
+ }
313
+
260
314
  const mapOrSingleValue = this.#inner.get(key)
261
315
 
262
316
  if (mapOrSingleValue === undefined) {
package/src/multiset.ts CHANGED
@@ -209,6 +209,12 @@ export class MultiSet<T> {
209
209
  chunkedArrayPush(this.#inner, otherArray)
210
210
  }
211
211
 
212
+ add(item: T, multiplicity: number): void {
213
+ if (multiplicity !== 0) {
214
+ this.#inner.push([item, multiplicity])
215
+ }
216
+ }
217
+
212
218
  getInner(): MultiSetArray<T> {
213
219
  return this.#inner
214
220
  }
@@ -1,8 +1,7 @@
1
1
  import { map } from "./map.js"
2
2
  import { innerJoin } from "./join.js"
3
3
  import { consolidate } from "./consolidate.js"
4
- import type { KeyValue } from "../types.js"
5
- import type { IStreamBuilder, PipedOperator } from "../types"
4
+ import type { IStreamBuilder, KeyValue, PipedOperator } from "../types.js"
6
5
 
7
6
  /**
8
7
  * Filters the elements of a keyed stream, by keys of another stream.