@@ -9,6 +9,7 @@ import type { IStreamBuilder, PipedOperator } from "../types.js"
99export interface TopKWithFractionalIndexOptions {
1010 limit ?: number
1111 offset ?: number
12+ setSizeCallback ?: ( getSize : ( ) => number ) => void
1213}
1314
1415export type TopKChanges < V > = {
@@ -23,6 +24,7 @@ export type TopKChanges<V> = {
2324 * and returns changes to the topK.
2425 */
2526export interface TopK < V > {
27+ size : number
2628 insert : ( value : V ) => TopKChanges < V >
2729 delete : ( value : V ) => TopKChanges < V >
2830}
@@ -49,6 +51,13 @@ class TopKArray<V> implements TopK<V> {
4951 this . #comparator = comparator
5052 }
5153
54+ get size ( ) : number {
55+ const offset = this . #topKStart
56+ const limit = this . #topKEnd - this . #topKStart
57+ const available = this . #sortedValues. length - offset
58+ return Math . max ( 0 , Math . min ( limit , available ) )
59+ }
60+
5261 insert ( value : V ) : TopKChanges < V > {
5362 const result : TopKChanges < V > = { moveIn : null , moveOut : null }
5463
@@ -169,6 +178,8 @@ export class TopKWithFractionalIndexOperator<K, T> extends UnaryOperator<
169178 */
170179 #topK: TopK < TaggedValue < K , T > >
171180
181+ #limit: number
182+
172183 constructor (
173184 id : number ,
174185 inputA : DifferenceStreamReader < [ K , T ] > ,
@@ -177,7 +188,7 @@ export class TopKWithFractionalIndexOperator<K, T> extends UnaryOperator<
177188 options : TopKWithFractionalIndexOptions
178189 ) {
179190 super ( id , inputA , output )
180- const limit = options . limit ?? Infinity
191+ this . # limit = options . limit ?? Infinity
181192 const offset = options . offset ?? 0
182193 const compareTaggedValues = (
183194 a : TaggedValue < K , T > ,
@@ -193,7 +204,8 @@ export class TopKWithFractionalIndexOperator<K, T> extends UnaryOperator<
193204 const tieBreakerB = getTag ( b )
194205 return tieBreakerA - tieBreakerB
195206 }
196- this . #topK = this . createTopK ( offset , limit , compareTaggedValues )
207+ this . #topK = this . createTopK ( offset , this . #limit, compareTaggedValues )
208+ options . setSizeCallback ?.( ( ) => this . #topK. size )
197209 }
198210
199211 protected createTopK (
0 commit comments