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

orderBy.ts

70 lines2.2 KB

1import { topKWithFractionalIndex } from './topKWithFractionalIndex.js'
2import { consolidate } from './consolidate.js'
3import type { IStreamBuilder, KeyValue } from '../types.js'
4import type { SetSizeCallback } from './topKWithFractionalIndex.js'
5​
6export interface OrderByOptions<Ve> {
7 comparator?: (a: Ve, b: Ve) => number
8 limit?: number
9 offset?: number
11​
12type OrderByWithFractionalIndexOptions<Ve> = OrderByOptions<Ve> & {
13 setSizeCallback?: SetSizeCallback
14 setWindowFn?: (
15 windowFn: (options: { offset?: number; limit?: number }) => void,
16 ) => void
18​
19/**
20 * Orders the elements and limits the number of results, with optional offset and
21 * annotates the value with a fractional index.
22 * This requires a keyed stream, and uses the `topKWithFractionalIndex` operator to order all the elements.
23 *
24 * @param valueExtractor - A function that extracts the value to order by from the element
25 * @param options - An optional object containing comparator, limit and offset properties
26 * @returns A piped operator that orders the elements and limits the number of results
27 */
28export function orderByWithFractionalIndex<
29 T extends KeyValue<unknown, unknown>,
30 Ve = unknown,
31>(
32 valueExtractor: (
33 value: T extends KeyValue<unknown, infer V> ? V : never,
34 ) => Ve,
35 options?: OrderByWithFractionalIndexOptions<Ve>,
36) {
37 type KeyType = T extends KeyValue<infer K, unknown> ? K : never
38 type ValueType = T extends KeyValue<unknown, infer V> ? V : never
39​
40 const limit = options?.limit ?? Infinity
41 const offset = options?.offset ?? 0
42 const setSizeCallback = options?.setSizeCallback
43 const setWindowFn = options?.setWindowFn
44 const comparator =
45 options?.comparator ??
46 ((a, b) => {
47 // Default to JS like ordering
48 if (a === b) return 0
49 if (a < b) return -1
50 return 1
51 })
52​
53 return (
54 stream: IStreamBuilder<T>,
55 ): IStreamBuilder<[KeyType, [ValueType, string]]> => {
56 return stream.pipe(
57 topKWithFractionalIndex(
58 (a: ValueType, b: ValueType) =>
59 comparator(valueExtractor(a), valueExtractor(b)),
60 {
61 limit,
62 offset,
63 setSizeCallback,
64 setWindowFn,
65 },
66 ),
67 consolidate(),
68 )
69 }