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

Function orderBy

packages/db-ivm/src/operators/orderBy.ts:29–71  ·  view source on GitHub ↗
(
  valueExtractor: (
    value: T extends KeyValue<unknown, infer V> ? V : never,
  ) => Ve,
  options?: OrderByOptions<Ve>,
)

Source from the content-addressed store, hash-verified

27 * @returns A piped operator that orders the elements and limits the number of results
28 */
29export function orderBy<T extends KeyValue<unknown, unknown>, Ve = unknown>(
30 valueExtractor: (
31 value: T extends KeyValue<unknown, infer V> ? V : never,
32 ) => Ve,
33 options?: OrderByOptions<Ve>,
34) {
35 const limit = options?.limit ?? Infinity
36 const offset = options?.offset ?? 0
37 const comparator =
38 options?.comparator ??
39 ((a, b) => {
40 // Default to JS like ordering
41 if (a === b) return 0
42 if (a < b) return -1
43 return 1
44 })
45
46 return (stream: IStreamBuilder<T>): IStreamBuilder<T> => {
47 type KeyType = T extends KeyValue<infer K, unknown> ? K : never
48
49 return stream.pipe(
50 map(
51 ([key, value]) =>
52 [
53 null,
54 [
55 key,
56 valueExtractor(
57 value as T extends KeyValue<unknown, infer V> ? V : never,
58 ),
59 ],
60 ] as KeyValue<null, [KeyType, Ve]>,
61 ),
62 topK((a, b) => comparator(a[1], b[1]), { limit, offset }),
63 map(([_, [key]]) => [key, null] as KeyValue<KeyType, null>),
64 innerJoin(stream),
65 map(([key, value]) => {
66 return [key, value[1]] as T
67 }),
68 consolidate(),
69 )
70 }
71}
72
73/**
74 * Orders the elements and limits the number of results, with optional offset and

Callers 2

orderBy.test.tsFile · 0.85

Calls 7

mapFunction · 0.85
topKFunction · 0.85
comparatorFunction · 0.85
innerJoinFunction · 0.85
consolidateFunction · 0.85
pipeMethod · 0.80
valueExtractorFunction · 0.50

Tested by

no test coverage detected