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