@tanstack/db-ivm 0.1.0 → 0.1.2
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.
- package/dist/cjs/index.cjs +3 -0
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/operators/index.d.cts +1 -0
- package/dist/cjs/operators/orderBy.cjs +8 -19
- package/dist/cjs/operators/orderBy.cjs.map +1 -1
- package/dist/cjs/operators/orderBy.d.cts +6 -2
- package/dist/cjs/operators/orderByBTree.d.cts +1 -1
- package/dist/cjs/operators/tap.cjs +46 -0
- package/dist/cjs/operators/tap.cjs.map +1 -0
- package/dist/cjs/operators/tap.d.cts +18 -0
- package/dist/cjs/operators/topKWithFractionalIndex.cjs +49 -22
- package/dist/cjs/operators/topKWithFractionalIndex.cjs.map +1 -1
- package/dist/cjs/operators/topKWithFractionalIndex.d.cts +13 -14
- package/dist/cjs/operators/topKWithFractionalIndexBTree.d.cts +5 -5
- package/dist/esm/index.js +3 -0
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/operators/index.d.ts +1 -0
- package/dist/esm/operators/orderBy.d.ts +6 -2
- package/dist/esm/operators/orderBy.js +8 -19
- package/dist/esm/operators/orderBy.js.map +1 -1
- package/dist/esm/operators/orderByBTree.d.ts +1 -1
- package/dist/esm/operators/tap.d.ts +18 -0
- package/dist/esm/operators/tap.js +46 -0
- package/dist/esm/operators/tap.js.map +1 -0
- package/dist/esm/operators/topKWithFractionalIndex.d.ts +13 -14
- package/dist/esm/operators/topKWithFractionalIndex.js +49 -22
- package/dist/esm/operators/topKWithFractionalIndex.js.map +1 -1
- package/dist/esm/operators/topKWithFractionalIndexBTree.d.ts +5 -5
- package/package.json +1 -1
- package/src/operators/index.ts +1 -0
- package/src/operators/orderBy.ts +19 -31
- package/src/operators/tap.ts +53 -0
- package/src/operators/topKWithFractionalIndex.ts +83 -59
- package/src/operators/topKWithFractionalIndexBTree.ts +21 -19
|
@@ -68,6 +68,7 @@ function orderByWithIndex(valueExtractor, options) {
|
|
|
68
68
|
function orderByWithFractionalIndexBase(topKFunction, valueExtractor, options) {
|
|
69
69
|
const limit = (options == null ? void 0 : options.limit) ?? Infinity;
|
|
70
70
|
const offset = (options == null ? void 0 : options.offset) ?? 0;
|
|
71
|
+
const setSizeCallback = options == null ? void 0 : options.setSizeCallback;
|
|
71
72
|
const comparator = (options == null ? void 0 : options.comparator) ?? ((a, b) => {
|
|
72
73
|
if (a === b) return 0;
|
|
73
74
|
if (a < b) return -1;
|
|
@@ -75,26 +76,14 @@ function orderByWithFractionalIndexBase(topKFunction, valueExtractor, options) {
|
|
|
75
76
|
});
|
|
76
77
|
return (stream) => {
|
|
77
78
|
return stream.pipe(
|
|
78
|
-
|
|
79
|
-
(
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
)
|
|
86
|
-
]
|
|
87
|
-
]
|
|
79
|
+
topKFunction(
|
|
80
|
+
(a, b) => comparator(valueExtractor(a), valueExtractor(b)),
|
|
81
|
+
{
|
|
82
|
+
limit,
|
|
83
|
+
offset,
|
|
84
|
+
setSizeCallback
|
|
85
|
+
}
|
|
88
86
|
),
|
|
89
|
-
topKFunction((a, b) => comparator(a[1], b[1]), {
|
|
90
|
-
limit,
|
|
91
|
-
offset
|
|
92
|
-
}),
|
|
93
|
-
map(([_, [[key], index]]) => [key, index]),
|
|
94
|
-
innerJoin(stream),
|
|
95
|
-
map(([key, [index, value]]) => {
|
|
96
|
-
return [key, [value, index]];
|
|
97
|
-
}),
|
|
98
87
|
consolidate()
|
|
99
88
|
);
|
|
100
89
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"orderBy.js","sources":["../../../src/operators/orderBy.ts"],"sourcesContent":["import { topK, topKWithIndex } from \"./topK.js\"\nimport { topKWithFractionalIndex } from \"./topKWithFractionalIndex.js\"\nimport { map } from \"./map.js\"\nimport { innerJoin } from \"./join.js\"\nimport { consolidate } from \"./consolidate.js\"\nimport type { KeyValue } from \"../types.js\"\nimport type { IStreamBuilder } from \"../types\"\n\nexport interface OrderByOptions<Ve> {\n comparator?: (a: Ve, b: Ve) => number\n limit?: number\n offset?: number\n}\n\n/**\n * Orders the elements and limits the number of results, with optional offset\n * This requires a keyed stream, and uses the `topK` operator to order all the elements.\n *\n * @param valueExtractor - A function that extracts the value to order by from the element\n * @param options - An optional object containing comparator, limit and offset properties\n * @returns A piped operator that orders the elements and limits the number of results\n */\nexport function orderBy<T extends KeyValue<unknown, unknown>, Ve = unknown>(\n valueExtractor: (\n value: T extends KeyValue<unknown, infer V> ? V : never\n ) => Ve,\n options?: OrderByOptions<Ve>\n) {\n const limit = options?.limit ?? Infinity\n const offset = options?.offset ?? 0\n const comparator =\n options?.comparator ??\n ((a, b) => {\n // Default to JS like ordering\n if (a === b) return 0\n if (a < b) return -1\n return 1\n })\n\n return (stream: IStreamBuilder<T>): IStreamBuilder<T> => {\n type KeyType = T extends KeyValue<infer K, unknown> ? K : never\n\n return stream.pipe(\n map(\n ([key, value]) =>\n [\n null,\n [\n key,\n valueExtractor(\n value as T extends KeyValue<unknown, infer V> ? V : never\n ),\n ],\n ] as KeyValue<null, [KeyType, Ve]>\n ),\n topK((a, b) => comparator(a[1], b[1]), { limit, offset }),\n map(([_, [key]]) => [key, null] as KeyValue<KeyType, null>),\n innerJoin(stream),\n map(([key, value]) => {\n return [key, value[1]] as T\n }),\n consolidate()\n )\n }\n}\n\n/**\n * Orders the elements and limits the number of results, with optional offset and\n * annotates the value with the index.\n * This requires a keyed stream, and uses the `topKWithIndex` operator to order all the elements.\n *\n * @param valueExtractor - A function that extracts the value to order by from the element\n * @param options - An optional object containing comparator, limit and offset properties\n * @returns A piped operator that orders the elements and limits the number of results\n */\nexport function orderByWithIndex<\n T extends KeyValue<unknown, unknown>,\n Ve = unknown,\n>(\n valueExtractor: (\n value: T extends KeyValue<unknown, infer V> ? V : never\n ) => Ve,\n options?: OrderByOptions<Ve>\n) {\n const limit = options?.limit ?? Infinity\n const offset = options?.offset ?? 0\n const comparator =\n options?.comparator ??\n ((a, b) => {\n // Default to JS like ordering\n if (a === b) return 0\n if (a < b) return -1\n return 1\n })\n\n return (\n stream: IStreamBuilder<T>\n ): IStreamBuilder<\n KeyValue<\n T extends KeyValue<infer K, unknown> ? K : never,\n [T extends KeyValue<unknown, infer V> ? V : never, number]\n >\n > => {\n type KeyType = T extends KeyValue<infer K, unknown> ? K : never\n type ValueType = T extends KeyValue<unknown, infer V> ? V : never\n\n return stream.pipe(\n map(\n ([key, value]) =>\n [\n null,\n [\n key,\n valueExtractor(\n value as T extends KeyValue<unknown, infer V> ? V : never\n ),\n ],\n ] as KeyValue<null, [KeyType, Ve]>\n ),\n topKWithIndex((a, b) => comparator(a[1], b[1]), { limit, offset }),\n map(([_, [[key], index]]) => [key, index] as KeyValue<KeyType, number>),\n innerJoin(stream),\n map(([key, [index, value]]) => {\n return [key, [value, index]] as KeyValue<KeyType, [ValueType, number]>\n }),\n consolidate()\n )\n }\n}\n\nexport function orderByWithFractionalIndexBase<\n T extends KeyValue<unknown, unknown>,\n Ve = unknown,\n>(\n topKFunction: typeof topKWithFractionalIndex,\n valueExtractor: (\n value: T extends KeyValue<unknown, infer V> ? V : never\n ) => Ve,\n options?:
|
|
1
|
+
{"version":3,"file":"orderBy.js","sources":["../../../src/operators/orderBy.ts"],"sourcesContent":["import { topK, topKWithIndex } from \"./topK.js\"\nimport { topKWithFractionalIndex } from \"./topKWithFractionalIndex.js\"\nimport { map } from \"./map.js\"\nimport { innerJoin } from \"./join.js\"\nimport { consolidate } from \"./consolidate.js\"\nimport type { KeyValue } from \"../types.js\"\nimport type { IStreamBuilder } from \"../types\"\n\nexport interface OrderByOptions<Ve> {\n comparator?: (a: Ve, b: Ve) => number\n limit?: number\n offset?: number\n}\n\ntype OrderByWithFractionalIndexOptions<Ve> = OrderByOptions<Ve> & {\n setSizeCallback?: (getSize: () => number) => void\n}\n\n/**\n * Orders the elements and limits the number of results, with optional offset\n * This requires a keyed stream, and uses the `topK` operator to order all the elements.\n *\n * @param valueExtractor - A function that extracts the value to order by from the element\n * @param options - An optional object containing comparator, limit and offset properties\n * @returns A piped operator that orders the elements and limits the number of results\n */\nexport function orderBy<T extends KeyValue<unknown, unknown>, Ve = unknown>(\n valueExtractor: (\n value: T extends KeyValue<unknown, infer V> ? V : never\n ) => Ve,\n options?: OrderByOptions<Ve>\n) {\n const limit = options?.limit ?? Infinity\n const offset = options?.offset ?? 0\n const comparator =\n options?.comparator ??\n ((a, b) => {\n // Default to JS like ordering\n if (a === b) return 0\n if (a < b) return -1\n return 1\n })\n\n return (stream: IStreamBuilder<T>): IStreamBuilder<T> => {\n type KeyType = T extends KeyValue<infer K, unknown> ? K : never\n\n return stream.pipe(\n map(\n ([key, value]) =>\n [\n null,\n [\n key,\n valueExtractor(\n value as T extends KeyValue<unknown, infer V> ? V : never\n ),\n ],\n ] as KeyValue<null, [KeyType, Ve]>\n ),\n topK((a, b) => comparator(a[1], b[1]), { limit, offset }),\n map(([_, [key]]) => [key, null] as KeyValue<KeyType, null>),\n innerJoin(stream),\n map(([key, value]) => {\n return [key, value[1]] as T\n }),\n consolidate()\n )\n }\n}\n\n/**\n * Orders the elements and limits the number of results, with optional offset and\n * annotates the value with the index.\n * This requires a keyed stream, and uses the `topKWithIndex` operator to order all the elements.\n *\n * @param valueExtractor - A function that extracts the value to order by from the element\n * @param options - An optional object containing comparator, limit and offset properties\n * @returns A piped operator that orders the elements and limits the number of results\n */\nexport function orderByWithIndex<\n T extends KeyValue<unknown, unknown>,\n Ve = unknown,\n>(\n valueExtractor: (\n value: T extends KeyValue<unknown, infer V> ? V : never\n ) => Ve,\n options?: OrderByOptions<Ve>\n) {\n const limit = options?.limit ?? Infinity\n const offset = options?.offset ?? 0\n const comparator =\n options?.comparator ??\n ((a, b) => {\n // Default to JS like ordering\n if (a === b) return 0\n if (a < b) return -1\n return 1\n })\n\n return (\n stream: IStreamBuilder<T>\n ): IStreamBuilder<\n KeyValue<\n T extends KeyValue<infer K, unknown> ? K : never,\n [T extends KeyValue<unknown, infer V> ? V : never, number]\n >\n > => {\n type KeyType = T extends KeyValue<infer K, unknown> ? K : never\n type ValueType = T extends KeyValue<unknown, infer V> ? V : never\n\n return stream.pipe(\n map(\n ([key, value]) =>\n [\n null,\n [\n key,\n valueExtractor(\n value as T extends KeyValue<unknown, infer V> ? V : never\n ),\n ],\n ] as KeyValue<null, [KeyType, Ve]>\n ),\n topKWithIndex((a, b) => comparator(a[1], b[1]), { limit, offset }),\n map(([_, [[key], index]]) => [key, index] as KeyValue<KeyType, number>),\n innerJoin(stream),\n map(([key, [index, value]]) => {\n return [key, [value, index]] as KeyValue<KeyType, [ValueType, number]>\n }),\n consolidate()\n )\n }\n}\n\nexport function orderByWithFractionalIndexBase<\n T extends KeyValue<unknown, unknown>,\n Ve = unknown,\n>(\n topKFunction: typeof topKWithFractionalIndex,\n valueExtractor: (\n value: T extends KeyValue<unknown, infer V> ? V : never\n ) => Ve,\n options?: OrderByWithFractionalIndexOptions<Ve>\n) {\n type KeyType = T extends KeyValue<infer K, unknown> ? K : never\n type ValueType = T extends KeyValue<unknown, infer V> ? V : never\n\n const limit = options?.limit ?? Infinity\n const offset = options?.offset ?? 0\n const setSizeCallback = options?.setSizeCallback\n const comparator =\n options?.comparator ??\n ((a, b) => {\n // Default to JS like ordering\n if (a === b) return 0\n if (a < b) return -1\n return 1\n })\n\n return (\n stream: IStreamBuilder<T>\n ): IStreamBuilder<[KeyType, [ValueType, string]]> => {\n return stream.pipe(\n topKFunction(\n (a: ValueType, b: ValueType) =>\n comparator(valueExtractor(a), valueExtractor(b)),\n {\n limit,\n offset,\n setSizeCallback,\n }\n ),\n consolidate()\n )\n }\n}\n\n/**\n * Orders the elements and limits the number of results, with optional offset and\n * annotates the value with a fractional index.\n * This requires a keyed stream, and uses the `topKWithFractionalIndex` operator to order all the elements.\n *\n * @param valueExtractor - A function that extracts the value to order by from the element\n * @param options - An optional object containing comparator, limit and offset properties\n * @returns A piped operator that orders the elements and limits the number of results\n */\nexport function orderByWithFractionalIndex<\n T extends KeyValue<unknown, unknown>,\n Ve = unknown,\n>(\n valueExtractor: (\n value: T extends KeyValue<unknown, infer V> ? V : never\n ) => Ve,\n options?: OrderByWithFractionalIndexOptions<Ve>\n) {\n return orderByWithFractionalIndexBase(\n topKWithFractionalIndex,\n valueExtractor,\n options\n )\n}\n"],"names":[],"mappings":";;;;;AA0BO,SAAS,QACd,gBAGA,SACA;AACA,QAAM,SAAQ,mCAAS,UAAS;AAChC,QAAM,UAAS,mCAAS,WAAU;AAClC,QAAM,cACJ,mCAAS,gBACR,CAAC,GAAG,MAAM;AAET,QAAI,MAAM,EAAG,QAAO;AACpB,QAAI,IAAI,EAAG,QAAO;AAClB,WAAO;AAAA,EACT;AAEF,SAAO,CAAC,WAAiD;AAGvD,WAAO,OAAO;AAAA,MACZ;AAAA,QACE,CAAC,CAAC,KAAK,KAAK,MACV;AAAA,UACE;AAAA,UACA;AAAA,YACE;AAAA,YACA;AAAA,cACE;AAAA,YAAA;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,MAEJ,KAAK,CAAC,GAAG,MAAM,WAAW,EAAE,CAAC,GAAG,EAAE,CAAC,CAAC,GAAG,EAAE,OAAO,QAAQ;AAAA,MACxD,IAAI,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,IAAI,CAA4B;AAAA,MAC1D,UAAU,MAAM;AAAA,MAChB,IAAI,CAAC,CAAC,KAAK,KAAK,MAAM;AACpB,eAAO,CAAC,KAAK,MAAM,CAAC,CAAC;AAAA,MACvB,CAAC;AAAA,MACD,YAAA;AAAA,IAAY;AAAA,EAEhB;AACF;AAWO,SAAS,iBAId,gBAGA,SACA;AACA,QAAM,SAAQ,mCAAS,UAAS;AAChC,QAAM,UAAS,mCAAS,WAAU;AAClC,QAAM,cACJ,mCAAS,gBACR,CAAC,GAAG,MAAM;AAET,QAAI,MAAM,EAAG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A;AAAA,EAAA;AAEJ;"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { KeyValue } from '../types.js';
|
|
2
2
|
import { OrderByOptions } from './orderBy.js';
|
|
3
|
-
export declare function orderByWithFractionalIndexBTree<T extends KeyValue<unknown, unknown>, Ve = unknown>(valueExtractor: (value: T extends KeyValue<unknown, infer V> ? V : never) => Ve, options?: OrderByOptions<Ve>): (stream: import('../types.js').IStreamBuilder<T>) => import('../types.js').IStreamBuilder<
|
|
3
|
+
export declare function orderByWithFractionalIndexBTree<T extends KeyValue<unknown, unknown>, Ve = unknown>(valueExtractor: (value: T extends KeyValue<unknown, infer V> ? V : never) => Ve, options?: OrderByOptions<Ve>): (stream: import('../types.js').IStreamBuilder<T>) => import('../types.js').IStreamBuilder<[T extends KeyValue<infer K, unknown> ? K : never, [T extends KeyValue<unknown, infer V> ? V : never, string]]>;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { DifferenceStreamWriter, LinearUnaryOperator, DifferenceStreamReader } from '../graph.js';
|
|
2
|
+
import { PipedOperator } from '../types.js';
|
|
3
|
+
import { MultiSet } from '../multiset.js';
|
|
4
|
+
/**
|
|
5
|
+
* Operator that applies a function to each element in the input stream
|
|
6
|
+
*/
|
|
7
|
+
export declare class TapOperator<T> extends LinearUnaryOperator<T, T> {
|
|
8
|
+
#private;
|
|
9
|
+
constructor(id: number, inputA: DifferenceStreamReader<T>, output: DifferenceStreamWriter<T>, f: (data: T) => void);
|
|
10
|
+
inner(collection: MultiSet<T>): MultiSet<T>;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Invokes a function for each element in the input stream.
|
|
14
|
+
* This operator doesn't modify the stream and is used to perform side effects.
|
|
15
|
+
* @param f - The function to invoke on each element
|
|
16
|
+
* @returns The input stream
|
|
17
|
+
*/
|
|
18
|
+
export declare function tap<T>(f: (data: T) => void): PipedOperator<T, T>;
|
|
@@ -0,0 +1,46 @@
|
|
|
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
|
+
import { LinearUnaryOperator, DifferenceStreamWriter } from "../graph.js";
|
|
10
|
+
import { StreamBuilder } from "../d2.js";
|
|
11
|
+
class TapOperator extends LinearUnaryOperator {
|
|
12
|
+
constructor(id, inputA, output, f) {
|
|
13
|
+
super(id, inputA, output);
|
|
14
|
+
__privateAdd(this, _f);
|
|
15
|
+
__privateSet(this, _f, f);
|
|
16
|
+
}
|
|
17
|
+
inner(collection) {
|
|
18
|
+
return collection.map((data) => {
|
|
19
|
+
__privateGet(this, _f).call(this, data);
|
|
20
|
+
return data;
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
_f = new WeakMap();
|
|
25
|
+
function tap(f) {
|
|
26
|
+
return (stream) => {
|
|
27
|
+
const output = new StreamBuilder(
|
|
28
|
+
stream.graph,
|
|
29
|
+
new DifferenceStreamWriter()
|
|
30
|
+
);
|
|
31
|
+
const operator = new TapOperator(
|
|
32
|
+
stream.graph.getNextOperatorId(),
|
|
33
|
+
stream.connectReader(),
|
|
34
|
+
output.writer,
|
|
35
|
+
f
|
|
36
|
+
);
|
|
37
|
+
stream.graph.addOperator(operator);
|
|
38
|
+
stream.graph.addStream(output.connectReader());
|
|
39
|
+
return output;
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
export {
|
|
43
|
+
TapOperator,
|
|
44
|
+
tap
|
|
45
|
+
};
|
|
46
|
+
//# sourceMappingURL=tap.js.map
|
|
@@ -0,0 +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 element in the input stream\n */\nexport class TapOperator<T> extends LinearUnaryOperator<T, T> {\n #f: (data: T) => void\n\n constructor(\n id: number,\n inputA: DifferenceStreamReader<T>,\n output: DifferenceStreamWriter<T>,\n f: (data: T) => void\n ) {\n super(id, inputA, output)\n this.#f = f\n }\n\n inner(collection: MultiSet<T>): MultiSet<T> {\n return collection.map((data) => {\n this.#f(data)\n return data\n })\n }\n}\n\n/**\n * Invokes a function for each element 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 element\n * @returns The input stream\n */\nexport function tap<T>(f: (data: 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 stream.graph.addStream(output.connectReader())\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,WAAO,WAAW,IAAI,CAAC,SAAS;AAC9B,yBAAK,IAAL,WAAQ;AACR,aAAO;AAAA,IACT,CAAC;AAAA,EACH;AACF;AAlBE;AA0BK,SAAS,IAAO,GAA2C;AAChE,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,MAAM,UAAU,OAAO,cAAA,CAAe;AAC7C,WAAO;AAAA,EACT;AACF;"}
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { DifferenceStreamWriter, UnaryOperator, DifferenceStreamReader } from '../graph.js';
|
|
2
|
-
import {
|
|
2
|
+
import { PipedOperator } from '../types.js';
|
|
3
3
|
export interface TopKWithFractionalIndexOptions {
|
|
4
4
|
limit?: number;
|
|
5
5
|
offset?: number;
|
|
6
|
+
setSizeCallback?: (getSize: () => number) => void;
|
|
6
7
|
}
|
|
7
8
|
export type TopKChanges<V> = {
|
|
8
9
|
/** Indicates which element moves into the topK (if any) */
|
|
@@ -15,6 +16,7 @@ export type TopKChanges<V> = {
|
|
|
15
16
|
* and returns changes to the topK.
|
|
16
17
|
*/
|
|
17
18
|
export interface TopK<V> {
|
|
19
|
+
size: number;
|
|
18
20
|
insert: (value: V) => TopKChanges<V>;
|
|
19
21
|
delete: (value: V) => TopKChanges<V>;
|
|
20
22
|
}
|
|
@@ -23,26 +25,23 @@ export interface TopK<V> {
|
|
|
23
25
|
* This operator maintains fractional indices for sorted elements
|
|
24
26
|
* and only updates indices when elements move position
|
|
25
27
|
*/
|
|
26
|
-
export declare class TopKWithFractionalIndexOperator<K,
|
|
28
|
+
export declare class TopKWithFractionalIndexOperator<K, T> extends UnaryOperator<[
|
|
27
29
|
K,
|
|
28
|
-
|
|
30
|
+
T
|
|
29
31
|
], [
|
|
30
32
|
K,
|
|
31
|
-
IndexedValue<
|
|
33
|
+
IndexedValue<T>
|
|
32
34
|
]> {
|
|
33
35
|
#private;
|
|
34
|
-
constructor(id: number, inputA: DifferenceStreamReader<[K,
|
|
35
|
-
protected createTopK(offset: number, limit: number, comparator: (a: TaggedValue<
|
|
36
|
+
constructor(id: number, inputA: DifferenceStreamReader<[K, T]>, output: DifferenceStreamWriter<[K, IndexedValue<T>]>, comparator: (a: T, b: T) => number, options: TopKWithFractionalIndexOptions);
|
|
37
|
+
protected createTopK(offset: number, limit: number, comparator: (a: TaggedValue<K, T>, b: TaggedValue<K, T>) => number): TopK<TaggedValue<K, T>>;
|
|
36
38
|
run(): void;
|
|
37
|
-
processElement(key: K, value:
|
|
39
|
+
processElement(key: K, value: T, multiplicity: number, result: Array<[[K, IndexedValue<T>], number]>): void;
|
|
40
|
+
private getMultiplicity;
|
|
41
|
+
private addKey;
|
|
38
42
|
}
|
|
39
43
|
/**
|
|
40
44
|
* Limits the number of results based on a comparator, with optional offset.
|
|
41
|
-
* This works on a keyed stream, where the key is the first element of the tuple.
|
|
42
|
-
* The ordering is within a key group, i.e. elements are sorted within a key group
|
|
43
|
-
* and the limit + offset is applied to that sorted group.
|
|
44
|
-
* To order the entire stream, key by the same value for all elements such as null.
|
|
45
|
-
*
|
|
46
45
|
* Uses fractional indexing to minimize the number of changes when elements move positions.
|
|
47
46
|
* Each element is assigned a fractional index that is lexicographically sortable.
|
|
48
47
|
* When elements move, only the indices of the moved elements are updated, not all elements.
|
|
@@ -51,11 +50,11 @@ export declare class TopKWithFractionalIndexOperator<K, V1> extends UnaryOperato
|
|
|
51
50
|
* @param options - An optional object containing limit and offset properties
|
|
52
51
|
* @returns A piped operator that orders the elements and limits the number of results
|
|
53
52
|
*/
|
|
54
|
-
export declare function topKWithFractionalIndex<KType
|
|
53
|
+
export declare function topKWithFractionalIndex<KType, T>(comparator: (a: T, b: T) => number, options?: TopKWithFractionalIndexOptions): PipedOperator<[KType, T], [KType, IndexedValue<T>]>;
|
|
55
54
|
export type FractionalIndex = string;
|
|
56
55
|
export type IndexedValue<V> = [V, FractionalIndex];
|
|
57
56
|
export declare function indexedValue<V>(value: V, index: FractionalIndex): IndexedValue<V>;
|
|
58
57
|
export declare function getValue<V>(indexedVal: IndexedValue<V>): V;
|
|
59
58
|
export declare function getIndex<V>(indexedVal: IndexedValue<V>): FractionalIndex;
|
|
60
59
|
export type Tag = number;
|
|
61
|
-
export type TaggedValue<V> = [V, Tag];
|
|
60
|
+
export type TaggedValue<K, V> = [K, V, Tag];
|
|
@@ -6,12 +6,11 @@ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read fr
|
|
|
6
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
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
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;
|
|
9
|
+
var _sortedValues, _comparator, _topKStart, _topKEnd, _TopKArray_instances, findIndex_fn, _index, _topK, _limit;
|
|
10
10
|
import { generateKeyBetween } from "fractional-indexing";
|
|
11
11
|
import { UnaryOperator, DifferenceStreamWriter } from "../graph.js";
|
|
12
12
|
import { StreamBuilder } from "../d2.js";
|
|
13
13
|
import { MultiSet } from "../multiset.js";
|
|
14
|
-
import { Index } from "../indexes.js";
|
|
15
14
|
import { binarySearch, globalObjectIdGenerator } from "../utils.js";
|
|
16
15
|
class TopKArray {
|
|
17
16
|
constructor(offset, limit, comparator) {
|
|
@@ -24,6 +23,12 @@ class TopKArray {
|
|
|
24
23
|
__privateSet(this, _topKEnd, offset + limit);
|
|
25
24
|
__privateSet(this, _comparator, comparator);
|
|
26
25
|
}
|
|
26
|
+
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;
|
|
30
|
+
return Math.max(0, Math.min(limit, available));
|
|
31
|
+
}
|
|
27
32
|
insert(value) {
|
|
28
33
|
const result = { moveIn: null, moveOut: null };
|
|
29
34
|
const index = __privateMethod(this, _TopKArray_instances, findIndex_fn).call(this, value);
|
|
@@ -88,17 +93,20 @@ findIndex_fn = function(value) {
|
|
|
88
93
|
};
|
|
89
94
|
class TopKWithFractionalIndexOperator extends UnaryOperator {
|
|
90
95
|
constructor(id, inputA, output, comparator, options) {
|
|
96
|
+
var _a;
|
|
91
97
|
super(id, inputA, output);
|
|
92
|
-
__privateAdd(this, _index, new
|
|
98
|
+
__privateAdd(this, _index, /* @__PURE__ */ new Map());
|
|
99
|
+
// maps keys to their multiplicity
|
|
93
100
|
/**
|
|
94
101
|
* topK data structure that supports insertions and deletions
|
|
95
102
|
* and returns changes to the topK.
|
|
96
103
|
*/
|
|
97
104
|
__privateAdd(this, _topK);
|
|
98
|
-
|
|
105
|
+
__privateAdd(this, _limit);
|
|
106
|
+
__privateSet(this, _limit, options.limit ?? Infinity);
|
|
99
107
|
const offset = options.offset ?? 0;
|
|
100
108
|
const compareTaggedValues = (a, b) => {
|
|
101
|
-
const valueComparison = comparator(
|
|
109
|
+
const valueComparison = comparator(getVal(a), getVal(b));
|
|
102
110
|
if (valueComparison !== 0) {
|
|
103
111
|
return valueComparison;
|
|
104
112
|
}
|
|
@@ -106,7 +114,8 @@ class TopKWithFractionalIndexOperator extends UnaryOperator {
|
|
|
106
114
|
const tieBreakerB = getTag(b);
|
|
107
115
|
return tieBreakerA - tieBreakerB;
|
|
108
116
|
};
|
|
109
|
-
__privateSet(this, _topK, this.createTopK(offset,
|
|
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);
|
|
110
119
|
}
|
|
111
120
|
createTopK(offset, limit, comparator) {
|
|
112
121
|
return new TopKArray(offset, limit, comparator);
|
|
@@ -124,33 +133,51 @@ class TopKWithFractionalIndexOperator extends UnaryOperator {
|
|
|
124
133
|
}
|
|
125
134
|
}
|
|
126
135
|
processElement(key, value, multiplicity, result) {
|
|
127
|
-
const oldMultiplicity =
|
|
128
|
-
__privateGet(this, _index).addValue(key, [value, multiplicity]);
|
|
129
|
-
const newMultiplicity = __privateGet(this, _index).getMultiplicity(key, value);
|
|
136
|
+
const { oldMultiplicity, newMultiplicity } = this.addKey(key, multiplicity);
|
|
130
137
|
let res = {
|
|
131
138
|
moveIn: null,
|
|
132
139
|
moveOut: null
|
|
133
140
|
};
|
|
134
141
|
if (oldMultiplicity <= 0 && newMultiplicity > 0) {
|
|
135
|
-
const taggedValue = tagValue(value);
|
|
142
|
+
const taggedValue = tagValue(key, value);
|
|
136
143
|
res = __privateGet(this, _topK).insert(taggedValue);
|
|
137
144
|
} else if (oldMultiplicity > 0 && newMultiplicity <= 0) {
|
|
138
|
-
const taggedValue = tagValue(value);
|
|
145
|
+
const taggedValue = tagValue(key, value);
|
|
139
146
|
res = __privateGet(this, _topK).delete(taggedValue);
|
|
140
147
|
} else ;
|
|
141
148
|
if (res.moveIn) {
|
|
142
|
-
const
|
|
143
|
-
|
|
149
|
+
const index = getIndex(res.moveIn);
|
|
150
|
+
const taggedValue = getValue(res.moveIn);
|
|
151
|
+
const k = getKey(taggedValue);
|
|
152
|
+
const val = getVal(taggedValue);
|
|
153
|
+
result.push([[k, [val, index]], 1]);
|
|
144
154
|
}
|
|
145
155
|
if (res.moveOut) {
|
|
146
|
-
const
|
|
147
|
-
|
|
156
|
+
const index = getIndex(res.moveOut);
|
|
157
|
+
const taggedValue = getValue(res.moveOut);
|
|
158
|
+
const k = getKey(taggedValue);
|
|
159
|
+
const val = getVal(taggedValue);
|
|
160
|
+
result.push([[k, [val, index]], -1]);
|
|
148
161
|
}
|
|
149
162
|
return;
|
|
150
163
|
}
|
|
164
|
+
getMultiplicity(key) {
|
|
165
|
+
return __privateGet(this, _index).get(key) ?? 0;
|
|
166
|
+
}
|
|
167
|
+
addKey(key, multiplicity) {
|
|
168
|
+
const oldMultiplicity = this.getMultiplicity(key);
|
|
169
|
+
const newMultiplicity = oldMultiplicity + multiplicity;
|
|
170
|
+
if (newMultiplicity === 0) {
|
|
171
|
+
__privateGet(this, _index).delete(key);
|
|
172
|
+
} else {
|
|
173
|
+
__privateGet(this, _index).set(key, newMultiplicity);
|
|
174
|
+
}
|
|
175
|
+
return { oldMultiplicity, newMultiplicity };
|
|
176
|
+
}
|
|
151
177
|
}
|
|
152
178
|
_index = new WeakMap();
|
|
153
179
|
_topK = new WeakMap();
|
|
180
|
+
_limit = new WeakMap();
|
|
154
181
|
function topKWithFractionalIndex(comparator, options) {
|
|
155
182
|
const opts = options || {};
|
|
156
183
|
return (stream) => {
|
|
@@ -179,18 +206,18 @@ function getValue(indexedVal) {
|
|
|
179
206
|
function getIndex(indexedVal) {
|
|
180
207
|
return indexedVal[1];
|
|
181
208
|
}
|
|
182
|
-
function
|
|
183
|
-
return [
|
|
209
|
+
function tagValue(key, value) {
|
|
210
|
+
return [key, value, globalObjectIdGenerator.getId(key)];
|
|
184
211
|
}
|
|
185
|
-
function
|
|
186
|
-
return [value, globalObjectIdGenerator.getId(value)];
|
|
187
|
-
}
|
|
188
|
-
function untagValue(tieBreakerTaggedValue) {
|
|
212
|
+
function getKey(tieBreakerTaggedValue) {
|
|
189
213
|
return tieBreakerTaggedValue[0];
|
|
190
214
|
}
|
|
191
|
-
function
|
|
215
|
+
function getVal(tieBreakerTaggedValue) {
|
|
192
216
|
return tieBreakerTaggedValue[1];
|
|
193
217
|
}
|
|
218
|
+
function getTag(tieBreakerTaggedValue) {
|
|
219
|
+
return tieBreakerTaggedValue[2];
|
|
220
|
+
}
|
|
194
221
|
export {
|
|
195
222
|
TopKWithFractionalIndexOperator,
|
|
196
223
|
getIndex,
|
|
@@ -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 { Index } from \"../indexes.js\"\nimport { binarySearch, globalObjectIdGenerator } from \"../utils.js\"\nimport type { DifferenceStreamReader } from \"../graph.js\"\nimport type { IStreamBuilder, KeyValue, PipedOperator } from \"../types.js\"\n\nexport interface TopKWithFractionalIndexOptions {\n limit?: number\n offset?: number\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 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 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, V1> extends UnaryOperator<\n [K, V1],\n [K, IndexedValue<V1>]\n> {\n #index = new Index<K, V1>()\n\n /**\n * topK data structure that supports insertions and deletions\n * and returns changes to the topK.\n */\n #topK: TopK<TaggedValue<V1>>\n\n constructor(\n id: number,\n inputA: DifferenceStreamReader<[K, V1]>,\n output: DifferenceStreamWriter<[K, [V1, string]]>,\n comparator: (a: V1, b: V1) => number,\n options: TopKWithFractionalIndexOptions\n ) {\n super(id, inputA, output)\n const limit = options.limit ?? Infinity\n const offset = options.offset ?? 0\n const compareTaggedValues = (a: TaggedValue<V1>, b: TaggedValue<V1>) => {\n // First compare on the value\n const valueComparison = comparator(untagValue(a), untagValue(b))\n if (valueComparison !== 0) {\n return valueComparison\n }\n // If the values are equal, compare on the tag (object identity)\n const tieBreakerA = getTag(a)\n const tieBreakerB = getTag(b)\n return tieBreakerA - tieBreakerB\n }\n this.#topK = this.createTopK(offset, limit, compareTaggedValues)\n }\n\n protected createTopK(\n offset: number,\n limit: number,\n comparator: (a: TaggedValue<V1>, b: TaggedValue<V1>) => number\n ): TopK<TaggedValue<V1>> {\n return new TopKArray(offset, limit, comparator)\n }\n\n run(): void {\n const result: Array<[[K, [V1, string]], 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: V1,\n multiplicity: number,\n result: Array<[[K, [V1, string]], number]>\n ): void {\n const oldMultiplicity = this.#index.getMultiplicity(key, value)\n this.#index.addValue(key, [value, multiplicity])\n const newMultiplicity = this.#index.getMultiplicity(key, value)\n\n let res: TopKChanges<TaggedValue<V1>> = {\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(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(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 valueWithoutTieBreaker = mapValue(res.moveIn, untagValue)\n result.push([[key, valueWithoutTieBreaker], 1])\n }\n\n if (res.moveOut) {\n const valueWithoutTieBreaker = mapValue(res.moveOut, untagValue)\n result.push([[key, valueWithoutTieBreaker], -1])\n }\n\n return\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 within 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 * 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<\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?: TopKWithFractionalIndexOptions\n): PipedOperator<T, KeyValue<KType, [V1Type, string]>> {\n const opts = options || {}\n\n return (\n stream: IStreamBuilder<T>\n ): IStreamBuilder<KeyValue<KType, [V1Type, string]>> => {\n const output = new StreamBuilder<KeyValue<KType, [V1Type, string]>>(\n stream.graph,\n new DifferenceStreamWriter<KeyValue<KType, [V1Type, string]>>()\n )\n const operator = new TopKWithFractionalIndexOperator<KType, V1Type>(\n stream.graph.getNextOperatorId(),\n stream.connectReader() as DifferenceStreamReader<KeyValue<KType, V1Type>>,\n output.writer,\n comparator,\n opts\n )\n stream.graph.addOperator(operator)\n stream.graph.addStream(output.connectReader())\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\nfunction mapValue<V, W>(\n indexedVal: IndexedValue<V>,\n f: (value: V) => W\n): IndexedValue<W> {\n return [f(getValue(indexedVal)), getIndex(indexedVal)]\n}\n\nexport type Tag = number\nexport type TaggedValue<V> = [V, Tag]\n\nfunction tagValue<V>(value: V): TaggedValue<V> {\n return [value, globalObjectIdGenerator.getId(value)]\n}\n\nfunction untagValue<V>(tieBreakerTaggedValue: TaggedValue<V>): V {\n return tieBreakerTaggedValue[0]\n}\n\nfunction getTag<V>(tieBreakerTaggedValue: TaggedValue<V>): Tag {\n return tieBreakerTaggedValue[1]\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;AAoCA,MAAM,UAAgC;AAAA,EAMpC,YACE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AO,MAAM,kBAAA;AAAA,MACb,OAAO,cAAA;AAAA,MACP,OAAO;AAAA,MACP;AAAA,MACA;AAAA,IAAA;AAEF,WAAO,MAAM,YAAY,QAAQ;AACjC,WAAO,MAAM,UAAU,OAAO,cAAA,CAAe;AAC7C,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;AAEA,SAAS,SACP,YACA,GACiB;AACjB,SAAO,CAAC,EAAE,SAAS,UAAU,CAAC,GAAG,SAAS,UAAU,CAAC;AACvD;AAKA,SAAS,SAAY,OAA0B;AAC7C,SAAO,CAAC,OAAO,wBAAwB,MAAM,KAAK,CAAC;AACrD;AAEA,SAAS,WAAc,uBAA0C;AAC/D,SAAO,sBAAsB,CAAC;AAChC;AAEA,SAAS,OAAU,uBAA4C;AAC7D,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 stream.graph.addStream(output.connectReader())\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,QAA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,QAAO,OAAO,GAAG;AAAA,IACxB,OAAO;AACL,yBAAK,QAAO,IAAI,KAAK,eAAe;AAAA,IACtC;AACA,WAAO,EAAE,iBAAiB,gBAAA;AAAA,EAC5B;AACF;AA5HE;AAMA;AAEA;AAgIK,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,MAAM,UAAU,OAAO,cAAA,CAAe;AAC7C,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,13 +1,13 @@
|
|
|
1
|
-
import { TopKWithFractionalIndexOperator, TaggedValue, TopK, TopKWithFractionalIndexOptions } from './topKWithFractionalIndex.js';
|
|
2
|
-
import {
|
|
1
|
+
import { TopKWithFractionalIndexOperator, IndexedValue, TaggedValue, TopK, TopKWithFractionalIndexOptions } from './topKWithFractionalIndex.js';
|
|
2
|
+
import { PipedOperator } from '../types.js';
|
|
3
3
|
export declare function loadBTree(): Promise<void>;
|
|
4
4
|
/**
|
|
5
5
|
* Operator for fractional indexed topK operations
|
|
6
6
|
* This operator maintains fractional indices for sorted elements
|
|
7
7
|
* and only updates indices when elements move position
|
|
8
8
|
*/
|
|
9
|
-
export declare class TopKWithFractionalIndexBTreeOperator<K,
|
|
10
|
-
protected createTopK(offset: number, limit: number, comparator: (a: TaggedValue<
|
|
9
|
+
export declare class TopKWithFractionalIndexBTreeOperator<K, T> extends TopKWithFractionalIndexOperator<K, T> {
|
|
10
|
+
protected createTopK(offset: number, limit: number, comparator: (a: TaggedValue<K, T>, b: TaggedValue<K, T>) => number): TopK<TaggedValue<K, T>>;
|
|
11
11
|
}
|
|
12
12
|
/**
|
|
13
13
|
* Limits the number of results based on a comparator, with optional offset.
|
|
@@ -24,4 +24,4 @@ export declare class TopKWithFractionalIndexBTreeOperator<K, V1> extends TopKWit
|
|
|
24
24
|
* @param options - An optional object containing limit and offset properties
|
|
25
25
|
* @returns A piped operator that orders the elements and limits the number of results
|
|
26
26
|
*/
|
|
27
|
-
export declare function topKWithFractionalIndexBTree<KType
|
|
27
|
+
export declare function topKWithFractionalIndexBTree<KType, T>(comparator: (a: T, b: T) => number, options?: TopKWithFractionalIndexOptions): PipedOperator<[KType, T], [KType, IndexedValue<T>]>;
|
package/package.json
CHANGED
package/src/operators/index.ts
CHANGED
package/src/operators/orderBy.ts
CHANGED
|
@@ -12,6 +12,10 @@ export interface OrderByOptions<Ve> {
|
|
|
12
12
|
offset?: number
|
|
13
13
|
}
|
|
14
14
|
|
|
15
|
+
type OrderByWithFractionalIndexOptions<Ve> = OrderByOptions<Ve> & {
|
|
16
|
+
setSizeCallback?: (getSize: () => number) => void
|
|
17
|
+
}
|
|
18
|
+
|
|
15
19
|
/**
|
|
16
20
|
* Orders the elements and limits the number of results, with optional offset
|
|
17
21
|
* This requires a keyed stream, and uses the `topK` operator to order all the elements.
|
|
@@ -136,10 +140,14 @@ export function orderByWithFractionalIndexBase<
|
|
|
136
140
|
valueExtractor: (
|
|
137
141
|
value: T extends KeyValue<unknown, infer V> ? V : never
|
|
138
142
|
) => Ve,
|
|
139
|
-
options?:
|
|
143
|
+
options?: OrderByWithFractionalIndexOptions<Ve>
|
|
140
144
|
) {
|
|
145
|
+
type KeyType = T extends KeyValue<infer K, unknown> ? K : never
|
|
146
|
+
type ValueType = T extends KeyValue<unknown, infer V> ? V : never
|
|
147
|
+
|
|
141
148
|
const limit = options?.limit ?? Infinity
|
|
142
149
|
const offset = options?.offset ?? 0
|
|
150
|
+
const setSizeCallback = options?.setSizeCallback
|
|
143
151
|
const comparator =
|
|
144
152
|
options?.comparator ??
|
|
145
153
|
((a, b) => {
|
|
@@ -151,37 +159,17 @@ export function orderByWithFractionalIndexBase<
|
|
|
151
159
|
|
|
152
160
|
return (
|
|
153
161
|
stream: IStreamBuilder<T>
|
|
154
|
-
): IStreamBuilder<
|
|
155
|
-
KeyValue<
|
|
156
|
-
T extends KeyValue<infer K, unknown> ? K : never,
|
|
157
|
-
[T extends KeyValue<unknown, infer V> ? V : never, string]
|
|
158
|
-
>
|
|
159
|
-
> => {
|
|
160
|
-
type KeyType = T extends KeyValue<infer K, unknown> ? K : never
|
|
161
|
-
type ValueType = T extends KeyValue<unknown, infer V> ? V : never
|
|
162
|
-
|
|
162
|
+
): IStreamBuilder<[KeyType, [ValueType, string]]> => {
|
|
163
163
|
return stream.pipe(
|
|
164
|
-
|
|
165
|
-
(
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
),
|
|
173
|
-
],
|
|
174
|
-
] as KeyValue<null, [KeyType, Ve]>
|
|
164
|
+
topKFunction(
|
|
165
|
+
(a: ValueType, b: ValueType) =>
|
|
166
|
+
comparator(valueExtractor(a), valueExtractor(b)),
|
|
167
|
+
{
|
|
168
|
+
limit,
|
|
169
|
+
offset,
|
|
170
|
+
setSizeCallback,
|
|
171
|
+
}
|
|
175
172
|
),
|
|
176
|
-
topKFunction((a, b) => comparator(a[1], b[1]), {
|
|
177
|
-
limit,
|
|
178
|
-
offset,
|
|
179
|
-
}),
|
|
180
|
-
map(([_, [[key], index]]) => [key, index] as KeyValue<KeyType, string>),
|
|
181
|
-
innerJoin(stream),
|
|
182
|
-
map(([key, [index, value]]) => {
|
|
183
|
-
return [key, [value, index]] as KeyValue<KeyType, [ValueType, string]>
|
|
184
|
-
}),
|
|
185
173
|
consolidate()
|
|
186
174
|
)
|
|
187
175
|
}
|
|
@@ -203,7 +191,7 @@ export function orderByWithFractionalIndex<
|
|
|
203
191
|
valueExtractor: (
|
|
204
192
|
value: T extends KeyValue<unknown, infer V> ? V : never
|
|
205
193
|
) => Ve,
|
|
206
|
-
options?:
|
|
194
|
+
options?: OrderByWithFractionalIndexOptions<Ve>
|
|
207
195
|
) {
|
|
208
196
|
return orderByWithFractionalIndexBase(
|
|
209
197
|
topKWithFractionalIndex,
|