Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

topK.ts

91 lines3.4 KB

1import { MultiSet } from '../multiset.js'
2import { reduce } from './reduce.js'
3import type { IStreamBuilder, KeyValue, PipedOperator } from '../types'
4​
5interface TopKOptions {
6 limit?: number
7 offset?: number
8}
9​
10/**
11 * Limits the number of results based on a comparator, with optional offset.
12 * This works on a keyed stream, where the key is the first element of the tuple
13 * The ordering is withing a key group, i.e. elements are sorted within a key group
14 * and the limit + offset is applied to that sorted group.
15 * To order the entire stream, key by the same value for all elements such as null.
16 *
17 * @param comparator - A function that compares two elements
18 * @param options - An optional object containing limit and offset properties
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 }
46​
47/**
48 * Limits the number of results based on a comparator, with optional offset.
49 * This works on a keyed stream, where the key is the first element of the tuple
50 * The ordering is withing a key group, i.e. elements are sorted within a key group
51 * and the limit + offset is applied to that sorted group.
52 * To order the entire stream, key by the same value for all elements such as null.
53 * Adds the index of the element to the result as [key, [value, index]]
54 *
55 * @param comparator - A function that compares two elements
56 * @param options - An optional object containing limit and offset properties
57 * @returns A piped operator that orders the elements and limits the number of results
58 */
59export function topKWithIndex<
60 KType extends (T extends KeyValue<infer K, infer _V> ? K : never),
61 V1Type extends (T extends KeyValue<KType, infer V> ? V : never),
62 T,
63>(
64 comparator: (a: V1Type, b: V1Type) => number,
65 options?: TopKOptions,
66): PipedOperator<T, KeyValue<KType, [V1Type, number]>> {
67 const limit = options?.limit ?? Infinity
68 const offset = options?.offset ?? 0
69​
70 return (
71 stream: IStreamBuilder<T>,
72 ): IStreamBuilder<KeyValue<KType, [V1Type, number]>> => {
73 const reduced = stream.pipe(
74 reduce<KType, V1Type, [V1Type, number], T>((values) => {
75 // `values` is a list of tuples, first element is the value, second is the multiplicity
76 const consolidated = new MultiSet(values).consolidate()
77 let i = offset
78 const sortedValues = consolidated
79 .getInner()
80 .sort((a, b) => comparator(a[0], b[0]))
81 .slice(offset, offset + limit)
82 .map(([value, multiplicity]): [[V1Type, number], number] => [
83 [value, i++],
84 multiplicity,
85 ])
86 return sortedValues
87 }),
88 )
89 return reduced
90 }