MCPcopy Create free account
hub / github.com/TanStack/db / topK

Function topK

packages/db-ivm/src/operators/topK.ts:21–45  ·  view source on GitHub ↗
(
  comparator: (a: V1Type, b: V1Type) => number,
  options?: TopKOptions,
)

Source from the content-addressed store, hash-verified

19 * @returns A piped operator that limits the number of results
20 */
21export 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.

Callers 3

orderByFunction · 0.85
topK.test.tsFile · 0.85

Calls 5

reduceFunction · 0.85
comparatorFunction · 0.85
pipeMethod · 0.80
consolidateMethod · 0.80
getInnerMethod · 0.80

Tested by

no test coverage detected