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