( comparator: (a: V1Type, b: V1Type) => number, options?: TopKOptions, )
| 19 | * @returns A piped operator that limits the number of results |
| 20 | */ |
| 21 | export function topK< |
| 22 | KType extends T extends KeyValue<infer K, infer _V> ? K : never, |
| 23 | V1Type extends T extends KeyValue<KType, infer V> ? V : never, |
| 24 | T, |
| 25 | >( |
| 26 | comparator: (a: V1Type, b: V1Type) => number, |
| 27 | options?: TopKOptions, |
| 28 | ): PipedOperator<T, T> { |
| 29 | const limit = options?.limit ?? Infinity |
| 30 | const offset = options?.offset ?? 0 |
| 31 | |
| 32 | return (stream: IStreamBuilder<T>): IStreamBuilder<T> => { |
| 33 | const reduced = stream.pipe( |
| 34 | reduce((values) => { |
| 35 | // `values` is a list of tuples, first element is the value, second is the multiplicity |
| 36 | const consolidated = new MultiSet(values).consolidate() |
| 37 | const sortedValues = consolidated |
| 38 | .getInner() |
| 39 | .sort((a, b) => comparator(a[0] as V1Type, b[0] as V1Type)) |
| 40 | return sortedValues.slice(offset, offset + limit) |
| 41 | }), |
| 42 | ) |
| 43 | return reduced as IStreamBuilder<T> |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | /** |
| 48 | * Limits the number of results based on a comparator, with optional offset. |
no test coverage detected