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

groupBy.ts

386 lines11.3 KB

1import { serializeValue } from '../utils.js'
2import { map } from './map.js'
3import { reduce } from './reduce.js'
4import type { IStreamBuilder, KeyValue } from '../types.js'
5​
6type GroupKey = Record<string, unknown>
7​
8type BasicAggregateFunction<T, R, V = unknown> = {
9 preMap: (data: T) => V
10 reduce: (values: Array<[V, number]>) => V
11 postMap?: (result: V) => R
13​
14type PipedAggregateFunction<T, R> = {
15 pipe: (stream: IStreamBuilder<T>) => IStreamBuilder<KeyValue<string, R>>
17​
18type AggregateFunction<T, R, V = unknown> =
19 BasicAggregateFunction<T, R, V> | PipedAggregateFunction<T, R>
20​
21type ExtractAggregateReturnType<T, A> =
22 A extends AggregateFunction<T, infer R, any> ? R : never
23​
24type AggregatesReturnType<T, A> = {
25 [K in keyof A]: ExtractAggregateReturnType<T, A[K]>
27​
28function isPipedAggregateFunction<T, R>(
29 aggregate: AggregateFunction<T, R>,
30): aggregate is PipedAggregateFunction<T, R> {
31 return `pipe` in aggregate
33​
34/**
35 * Groups data by key and applies multiple aggregate operations
36 * @param keyExtractor Function to extract grouping key from data
37 * @param aggregates Object mapping aggregate names to aggregate functions
38 */
39export function groupBy<
40 T,
41 K extends GroupKey,
42 A extends Record<string, AggregateFunction<T, any, any>>,
43>(keyExtractor: (data: T) => K, aggregates: A = {} as A) {
44 type ResultType = K & AggregatesReturnType<T, A>
45​
46 const basicAggregates = Object.fromEntries(
47 Object.entries(aggregates).filter(
48 ([_, aggregate]) => !isPipedAggregateFunction(aggregate),
49 ),
50 ) as Record<string, BasicAggregateFunction<T, any, any>>
51​
52 // @ts-expect-error - TODO: we don't use this yet, but we will
53 // eslint-disable-next-line @typescript-eslint/no-unused-vars
54 const pipedAggregates = Object.fromEntries(
55 Object.entries(aggregates).filter(([_, aggregate]) =>
56 isPipedAggregateFunction(aggregate),
57 ),
58 ) as Record<string, PipedAggregateFunction<T, any>>
59​
60 return (
61 stream: IStreamBuilder<T>,
62 ): IStreamBuilder<KeyValue<string, ResultType>> => {
63 // Special key to store the original key object
64 const KEY_SENTINEL = Symbol(`original_group_key`)
65​
66 // First map to extract keys and pre-aggregate values
67 const withKeysAndValues = stream.pipe(
68 map((data) => {
69 const key = keyExtractor(data)
70 const keyString = serializeValue(key)
71​
72 // Create values object with pre-aggregated values
73 const values: Record<string | symbol, unknown> = {}
74​
75 // Store the original key object
76 values[KEY_SENTINEL] = key
77​
78 // Add pre-aggregated values
79 for (const [name, aggregate] of Object.entries(basicAggregates)) {
80 values[name] = aggregate.preMap(data)
81 }
82​
83 return [keyString, values] as KeyValue<
84 string,
85 Record<string | symbol, unknown>
86 >
87 }),
88 )
89​
90 // Then reduce to compute aggregates
91 const reduced = withKeysAndValues.pipe(
92 reduce((values) => {
93 // Calculate total multiplicity to check if the group should exist
94 let totalMultiplicity = 0
95 for (const [_, multiplicity] of values) {
96 totalMultiplicity += multiplicity
97 }
98​
99 // If total multiplicity is 0 or negative, the group should be removed completely
100 if (totalMultiplicity <= 0) {
101 return []
102 }
103​
104 const result: Record<PropertyKey, unknown> = {}
105​
106 // Get the original key from first value in group
107 const originalKey = values[0]?.[0]?.[KEY_SENTINEL]
108 result[KEY_SENTINEL] = originalKey
109​
110 // Apply each aggregate function
111 for (const [name, aggregate] of Object.entries(basicAggregates)) {
112 const preValues = values.map(
113 ([v, m]) => [v[name], m] as [any, number],
114 )
115 result[name] = aggregate.reduce(preValues)
116 }
117​
118 return [[result, 1]]
119 }),
120 )
121​
122 // Finally map to extract the key and include all values
123 return reduced.pipe(
124 map(([keyString, values]) => {
125 // Extract the original key
126 const key = values[KEY_SENTINEL] as K
127​
128 // Create intermediate result with key values and aggregate results
129 const result: Record<string, unknown> = {}
130​
131 // Add key properties to result
132 Object.assign(result, key)
133​
134 // Apply postMap if provided
135 for (const [name, aggregate] of Object.entries(basicAggregates)) {
136 if (aggregate.postMap) {
137 result[name] = aggregate.postMap(values[name])
138 } else {
139 result[name] = values[name]
140 }
141 }
142​
143 // Return with the string key instead of the object
144 return [keyString, result] as KeyValue<string, ResultType>
145 }),
146 )
147 }
149​
150/**
151 * Creates a sum aggregate function
152 */
153export function sum<T>(
154 valueExtractor: (value: T) => number = (v) => v as unknown as number,
155): AggregateFunction<T, number, number> {
156 return {
157 preMap: (data: T) => valueExtractor(data),
158 reduce: (values: Array<[number, number]>) => {
159 let total = 0
160 for (const [value, multiplicity] of values) {
161 total += value * multiplicity
162 }
163 return total
164 },
165 }
167​
168/**
169 * Creates a count aggregate function
170 */
171export function count<T>(
172 valueExtractor: (value: T) => any = (v) => v,
173): AggregateFunction<T, number, number> {
174 return {
175 // Count only not-null values (the `== null` comparison gives true for both null and undefined)
176 preMap: (data: T) => (valueExtractor(data) == null ? 0 : 1),
177 reduce: (values: Array<[number, number]>) => {
178 let totalCount = 0
179 for (const [nullMultiplier, multiplicity] of values) {
180 totalCount += nullMultiplier * multiplicity
181 }
182 return totalCount
183 },
184 }
186​
187/**
188 * Creates an average aggregate function
189 */
190export function avg<T>(
191 valueExtractor: (value: T) => number = (v) => v as unknown as number,
192): AggregateFunction<T, number, { sum: number; count: number }> {
193 return {
194 preMap: (data: T) => ({
195 sum: valueExtractor(data),
196 count: 0,
197 }),
198 reduce: (values: Array<[{ sum: number; count: number }, number]>) => {
199 let totalSum = 0
200 let totalCount = 0
201 for (const [value, multiplicity] of values) {
202 totalSum += value.sum * multiplicity
203 totalCount += multiplicity
204 }
205 return {
206 sum: totalSum,
207 count: totalCount,
208 }
209 },
210 postMap: (result: { sum: number; count: number }) => {
211 return result.sum / result.count
212 },
213 }
215​
216type CanMinMax = number | Date | bigint | string
217​
218/**
219 * Creates a min aggregate function that computes the minimum value in a group
220 * @param valueExtractor Function to extract a comparable value from each data entry
221 */
222export function min<T extends CanMinMax>(): AggregateFunction<
223 T,
224 T | undefined,
225 T | undefined
227export function min<T, V extends CanMinMax>(
228 valueExtractor: (value: T) => V,
229): AggregateFunction<T, V | undefined, V | undefined>
230export function min<T, V extends CanMinMax>(
231 valueExtractor?: (value: T) => V,
232): AggregateFunction<T, V | undefined, V | undefined> {
233 const extractor = valueExtractor ?? ((v: T) => v as unknown as V)
234 return {
235 preMap: (data: T) => extractor(data),
236 reduce: (values) => {
237 let minValue: V | undefined
238 for (const [value, _multiplicity] of values) {
239 if (
240 value !== undefined &&
241 (minValue === undefined || value < minValue)
242 ) {
243 minValue = value
244 }
245 }
246 return minValue
247 },
248 }
250​
251/**
252 * Creates a max aggregate function that computes the maximum value in a group
253 * @param valueExtractor Function to extract a comparable value from each data entry
254 */
255export function max<T extends CanMinMax>(): AggregateFunction<
256 T,
257 T | undefined,
258 T | undefined
260export function max<T, V extends CanMinMax>(
261 valueExtractor: (value: T) => V,
262): AggregateFunction<T, V | undefined, V | undefined>
263export function max<T, V extends CanMinMax>(
264 valueExtractor?: (value: T) => V,
265): AggregateFunction<T, V | undefined, V | undefined> {
266 const extractor = valueExtractor ?? ((v: T) => v as unknown as V)
267 return {
268 preMap: (data: T) => extractor(data),
269 reduce: (values) => {
270 let maxValue: V | undefined
271 for (const [value, _multiplicity] of values) {
272 if (
273 value !== undefined &&
274 (maxValue === undefined || value > maxValue)
275 ) {
276 maxValue = value
277 }
278 }
279 return maxValue
280 },
281 }
283​
284/**
285 * Creates a median aggregate function that computes the middle value in a sorted group
286 * If there's an even number of values, returns the average of the two middle values
287 * @param valueExtractor Function to extract a numeric value from each data entry
288 */
289export function median<T>(
290 valueExtractor: (value: T) => number = (v) => v as unknown as number,
291): AggregateFunction<T, number, Array<number>> {
292 return {
293 preMap: (data: T) => [valueExtractor(data)],
294 reduce: (values: Array<[Array<number>, number]>) => {
295 // Flatten all values, taking multiplicity into account
296 const allValues: Array<number> = []
297 for (const [valueArray, multiplicity] of values) {
298 for (const value of valueArray) {
299 // Add each value multiple times based on multiplicity
300 for (let i = 0; i < multiplicity; i++) {
301 allValues.push(value)
302 }
303 }
304 }
305​
306 // Return empty array if no values
307 if (allValues.length === 0) {
308 return []
309 }
310​
311 // Sort values
312 allValues.sort((a, b) => a - b)
313​
314 return allValues
315 },
316 postMap: (result: Array<number>) => {
317 if (result.length === 0) return 0
318​
319 const mid = Math.floor(result.length / 2)
320​
321 // If even number of values, average the two middle values
322 if (result.length % 2 === 0) {
323 return (result[mid - 1]! + result[mid]!) / 2
324 }
325​
326 // If odd number of values, return the middle value
327 return result[mid]!
328 },
329 }
331​
332/**
333 * Creates a mode aggregate function that computes the most frequent value in a group
334 * If multiple values have the same highest frequency, returns the first one encountered
335 * @param valueExtractor Function to extract a value from each data entry
336 */
337export function mode<T>(
338 valueExtractor: (value: T) => number = (v) => v as unknown as number,
339): AggregateFunction<T, number, Map<number, number>> {
340 return {
341 preMap: (data: T) => {
342 const value = valueExtractor(data)
343 const frequencyMap = new Map<number, number>()
344 frequencyMap.set(value, 1)
345 return frequencyMap
346 },
347 reduce: (values: Array<[Map<number, number>, number]>) => {
348 // Combine all frequency maps
349 const combinedMap = new Map<number, number>()
350​
351 for (const [frequencyMap, multiplicity] of values) {
352 for (const [value, frequencyCount] of frequencyMap.entries()) {
353 const currentCount = combinedMap.get(value) || 0
354 combinedMap.set(value, currentCount + frequencyCount * multiplicity)
355 }
356 }
357​
358 return combinedMap
359 },
360 postMap: (result: Map<number, number>) => {
361 if (result.size === 0) return 0
362​
363 let modeValue = 0
364 let maxFrequency = 0
365​
366 for (const [value, frequency] of result.entries()) {
367 if (frequency > maxFrequency) {
368 maxFrequency = frequency
369 modeValue = value
370 }
371 }
372​
373 return modeValue
374 },
375 }
377​
378export const groupByOperators = {
379 sum,
380 count,
381 avg,
382 min,
383 max,
384 median,
385 mode,