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

Function orderByWithIndex

packages/db-ivm/src/operators/orderBy.ts:82–135  ·  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

80 * @returns A piped operator that orders the elements and limits the number of results
81 */
82export function orderByWithIndex<
83 T extends KeyValue<unknown, unknown>,
84 Ve = unknown,
85>(
86 valueExtractor: (
87 value: T extends KeyValue<unknown, infer V> ? V : never,
88 ) => Ve,
89 options?: OrderByOptions<Ve>,
90) {
91 const limit = options?.limit ?? Infinity
92 const offset = options?.offset ?? 0
93 const comparator =
94 options?.comparator ??
95 ((a, b) => {
96 // Default to JS like ordering
97 if (a === b) return 0
98 if (a < b) return -1
99 return 1
100 })
101
102 return (
103 stream: IStreamBuilder<T>,
104 ): IStreamBuilder<
105 KeyValue<
106 T extends KeyValue<infer K, unknown> ? K : never,
107 [T extends KeyValue<unknown, infer V> ? V : never, number]
108 >
109 > => {
110 type KeyType = T extends KeyValue<infer K, unknown> ? K : never
111 type ValueType = T extends KeyValue<unknown, infer V> ? V : never
112
113 return stream.pipe(
114 map(
115 ([key, value]) =>
116 [
117 null,
118 [
119 key,
120 valueExtractor(
121 value as T extends KeyValue<unknown, infer V> ? V : never,
122 ),
123 ],
124 ] as KeyValue<null, [KeyType, Ve]>,
125 ),
126 topKWithIndex((a, b) => comparator(a[1], b[1]), { limit, offset }),
127 map(([_, [[key], index]]) => [key, index] as KeyValue<KeyType, number>),
128 innerJoin(stream),
129 map(([key, [index, value]]) => {
130 return [key, [value, index]] as KeyValue<KeyType, [ValueType, number]>
131 }),
132 consolidate(),
133 )
134 }
135}
136
137export function orderByWithFractionalIndexBase<
138 T extends KeyValue<unknown, unknown>,

Callers 1

Calls 7

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

Tested by

no test coverage detected