Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

topKWithFractionalIndex.ts

128 lines4.1 KB

1import { UnaryOperator } from '../graph.js'
2import { unaryOperator } from '../unary-operator.js'
3import { MultiSet } from '../multiset.js'
4import {
5 TopKState,
6 handleMoveIn,
7 handleMoveOut,
8 topKBatch,
9} from './topKState.js'
10import { TopKArray, createKeyedComparator } from './topKArray.js'
11import type { IndexedValue } from './topKArray.js'
12import type {
13 DifferenceStreamReader,
14 DifferenceStreamWriter,
15} from '../graph.js'
16import type { PipedOperator } from '../types.js'
17​
18export interface TopKWithFractionalIndexOptions {
19 limit?: number
20 offset?: number
21 setSizeCallback?: SetSizeCallback
22 setWindowFn?: (
23 windowFn: (options: { offset?: number; limit?: number }) => void,
24 ) => void
26​
27/**
28 * Receives the window size. Given a predicate that holds for a prefix of the
29 * window order, the getter counts only the leading values that satisfy it.
30 */
31export type SetSizeCallback = (
32 getSize: (counts?: (value: unknown) => boolean) => number,
33) => void
34​
35/**
36 * Operator for fractional indexed topK operations
37 * This operator maintains fractional indices for sorted elements
38 * and only updates indices when elements move position
39 */
40export class TopKWithFractionalIndexOperator<
41 K extends string | number,
42 T,
43> extends UnaryOperator<[K, T], [K, IndexedValue<T>]> {
44 #state: TopKState<K, T>
45​
46 constructor(
47 id: number,
48 inputA: DifferenceStreamReader<[K, T]>,
49 output: DifferenceStreamWriter<[K, IndexedValue<T>]>,
50 comparator: (a: T, b: T) => number,
51 options: TopKWithFractionalIndexOptions,
52 ) {
53 super(id, inputA, output)
54 const limit = options.limit ?? Infinity
55 const offset = options.offset ?? 0
56 this.#state = new TopKState(
57 new TopKArray(offset, limit, createKeyedComparator(comparator)),
58 )
59 options.setSizeCallback?.((counts) =>
60 counts ? this.#state.countLeadingInWindow(counts) : this.#state.size,
61 )
62 options.setWindowFn?.(this.moveTopK.bind(this))
63 }
64​
65 /**
66 * Moves the topK window based on the provided offset and limit.
67 * Any changes to the topK are sent to the output.
68 */
69 moveTopK({ offset, limit }: { offset?: number; limit?: number }) {
70 const result: Array<[[K, IndexedValue<T>], number]> = []
71 const diff = this.#state.move({ offset, limit })
72​
73 diff.moveIns.forEach((moveIn) => handleMoveIn(moveIn, result))
74 diff.moveOuts.forEach((moveOut) => handleMoveOut(moveOut, result))
75​
76 if (diff.changes) {
77 // There are changes to the topK
78 // it could be that moveIns and moveOuts are empty
79 // because the collection is lazy, so we will run the graph again to load the data
80 this.output.sendData(new MultiSet(result))
81 }
82 }
83​
84 run(): void {
85 const result: Array<[[K, IndexedValue<T>], number]> = []
86 for (const [[key, value], multiplicity] of topKBatch(
87 this.inputMessages(),
88 )) {
89 this.processElement(key, value, multiplicity, result)
90 }
91​
92 if (result.length > 0) {
93 this.output.sendData(new MultiSet(result))
94 }
95 }
96​
97 processElement(
98 key: K,
99 value: T,
100 multiplicity: number,
101 result: Array<[[K, IndexedValue<T>], number]>,
102 ): void {
103 const changes = this.#state.processElement(key, value, multiplicity)
104 handleMoveIn(changes.moveIn, result)
105 handleMoveOut(changes.moveOut, result)
106 }
108​
109/**
110 * Limits the number of results based on a comparator, with optional offset.
111 * Uses fractional indexing to minimize the number of changes when elements move positions.
112 * Each element is assigned a fractional index that is lexicographically sortable.
113 * When elements move, only the indices of the moved elements are updated, not all elements.
114 *
115 * @param comparator - A function that compares two elements
116 * @param options - An optional object containing limit and offset properties
117 * @returns A piped operator that orders the elements and limits the number of results
118 */
119export function topKWithFractionalIndex<KType extends string | number, T>(
120 comparator: (a: T, b: T) => number,
121 options?: TopKWithFractionalIndexOptions,
122): PipedOperator<[KType, T], [KType, IndexedValue<T>]> {
123 return unaryOperator(
124 TopKWithFractionalIndexOperator<KType, T>,
125 comparator,
126 options || {},
127 )