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

groupBy.ts

354 lines10.3 KB

1import { map } from "./map.js"
2import { reduce } from "./reduce.js"
3import type { IStreamBuilder, KeyValue } from "../types.js"
4​
5type GroupKey = Record<string, unknown>
6​
7type BasicAggregateFunction<T, R, V = unknown> = {
8 preMap: (data: T) => V
9 reduce: (values: Array<[V, number]>) => V
10 postMap?: (result: V) => R
12​
13type PipedAggregateFunction<T, R> = {
14 pipe: (stream: IStreamBuilder<T>) => IStreamBuilder<KeyValue<string, R>>
16​
17type AggregateFunction<T, R, V = unknown> =
18 | BasicAggregateFunction<T, R, V>
19 | 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 = `__original_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 = JSON.stringify(key)
71​
72 // Create values object with pre-aggregated values
73 const values: Record<string, 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<string, Record<string, unknown>>
84 })
85 )
86​
87 // Then reduce to compute aggregates
88 const reduced = withKeysAndValues.pipe(
89 reduce((values) => {
90 // Calculate total multiplicity to check if the group should exist
91 let totalMultiplicity = 0
92 for (const [_, multiplicity] of values) {
93 totalMultiplicity += multiplicity
94 }
95​
96 // If total multiplicity is 0 or negative, the group should be removed completely
97 if (totalMultiplicity <= 0) {
98 return []
99 }
100​
101 const result: Record<string, unknown> = {}
102​
103 // Get the original key from first value in group
104 const originalKey = values[0]?.[0]?.[KEY_SENTINEL]
105 result[KEY_SENTINEL] = originalKey
106​
107 // Apply each aggregate function
108 for (const [name, aggregate] of Object.entries(basicAggregates)) {
109 const preValues = values.map(
110 ([v, m]) => [v[name], m] as [any, number]
111 )
112 result[name] = aggregate.reduce(preValues)
113 }
114​
115 return [[result, 1]]
116 })
117 )
118​
119 // Finally map to extract the key and include all values
120 return reduced.pipe(
121 map(([keyString, values]) => {
122 // Extract the original key
123 const key = values[KEY_SENTINEL] as K
124​
125 // Create intermediate result with key values and aggregate results
126 const result: Record<string, unknown> = {}
127​
128 // Add key properties to result
129 Object.assign(result, key)
130​
131 // Apply postMap if provided
132 for (const [name, aggregate] of Object.entries(basicAggregates)) {
133 if (aggregate.postMap) {
134 result[name] = aggregate.postMap(values[name])
135 } else {
136 result[name] = values[name]
137 }
138 }
139​
140 // Return with the string key instead of the object
141 return [keyString, result] as KeyValue<string, ResultType>
142 })
143 )
144 }
146​
147/**
148 * Creates a sum aggregate function
149 */
150export function sum<T>(
151 valueExtractor: (value: T) => number = (v) => v as unknown as number
152): AggregateFunction<T, number, number> {
153 return {
154 preMap: (data: T) => valueExtractor(data),
155 reduce: (values: Array<[number, number]>) => {
156 let total = 0
157 for (const [value, multiplicity] of values) {
158 total += value * multiplicity
159 }
160 return total
161 },
162 }
164​
165/**
166 * Creates a count aggregate function
167 */
168export function count<T>(): AggregateFunction<T, number, number> {
169 return {
170 preMap: () => 1,
171 reduce: (values: Array<[number, number]>) => {
172 let totalCount = 0
173 for (const [_, multiplicity] of values) {
174 totalCount += multiplicity
175 }
176 return totalCount
177 },
178 }
180​
181/**
182 * Creates an average aggregate function
183 */
184export function avg<T>(
185 valueExtractor: (value: T) => number = (v) => v as unknown as number
186): AggregateFunction<T, number, { sum: number; count: number }> {
187 return {
188 preMap: (data: T) => ({
189 sum: valueExtractor(data),
190 count: 0,
191 }),
192 reduce: (values: Array<[{ sum: number; count: number }, number]>) => {
193 let totalSum = 0
194 let totalCount = 0
195 for (const [value, multiplicity] of values) {
196 totalSum += value.sum * multiplicity
197 totalCount += multiplicity
198 }
199 return {
200 sum: totalSum,
201 count: totalCount,
202 }
203 },
204 postMap: (result: { sum: number; count: number }) => {
205 return result.sum / result.count
206 },
207 }
209​
210/**
211 * Creates a min aggregate function that computes the minimum value in a group
212 * @param valueExtractor Function to extract a numeric value from each data entry
213 */
214export function min<T>(
215 valueExtractor: (value: T) => number = (v) => v as unknown as number
216): AggregateFunction<T, number, number> {
217 return {
218 preMap: (data: T) => valueExtractor(data),
219 reduce: (values: Array<[number, number]>) => {
220 let minValue = Number.POSITIVE_INFINITY
221 for (const [value, _multiplicity] of values) {
222 if (value < minValue) {
223 minValue = value
224 }
225 }
226 return minValue === Number.POSITIVE_INFINITY ? 0 : minValue
227 },
228 }
230​
231/**
232 * Creates a max aggregate function that computes the maximum value in a group
233 * @param valueExtractor Function to extract a numeric value from each data entry
234 */
235export function max<T>(
236 valueExtractor: (value: T) => number = (v) => v as unknown as number
237): AggregateFunction<T, number, number> {
238 return {
239 preMap: (data: T) => valueExtractor(data),
240 reduce: (values: Array<[number, number]>) => {
241 let maxValue = Number.NEGATIVE_INFINITY
242 for (const [value, _multiplicity] of values) {
243 if (value > maxValue) {
244 maxValue = value
245 }
246 }
247 return maxValue === Number.NEGATIVE_INFINITY ? 0 : maxValue
248 },
249 }
251​
252/**
253 * Creates a median aggregate function that computes the middle value in a sorted group
254 * If there's an even number of values, returns the average of the two middle values
255 * @param valueExtractor Function to extract a numeric value from each data entry
256 */
257export function median<T>(
258 valueExtractor: (value: T) => number = (v) => v as unknown as number
259): AggregateFunction<T, number, Array<number>> {
260 return {
261 preMap: (data: T) => [valueExtractor(data)],
262 reduce: (values: Array<[Array<number>, number]>) => {
263 // Flatten all values, taking multiplicity into account
264 const allValues: Array<number> = []
265 for (const [valueArray, multiplicity] of values) {
266 for (const value of valueArray) {
267 // Add each value multiple times based on multiplicity
268 for (let i = 0; i < multiplicity; i++) {
269 allValues.push(value)
270 }
271 }
272 }
273​
274 // Return empty array if no values
275 if (allValues.length === 0) {
276 return []
277 }
278​
279 // Sort values
280 allValues.sort((a, b) => a - b)
281​
282 return allValues
283 },
284 postMap: (result: Array<number>) => {
285 if (result.length === 0) return 0
286​
287 const mid = Math.floor(result.length / 2)
288​
289 // If even number of values, average the two middle values
290 if (result.length % 2 === 0) {
291 return (result[mid - 1]! + result[mid]!) / 2
292 }
293​
294 // If odd number of values, return the middle value
295 return result[mid]!
296 },
297 }
299​
300/**
301 * Creates a mode aggregate function that computes the most frequent value in a group
302 * If multiple values have the same highest frequency, returns the first one encountered
303 * @param valueExtractor Function to extract a value from each data entry
304 */
305export function mode<T>(
306 valueExtractor: (value: T) => number = (v) => v as unknown as number
307): AggregateFunction<T, number, Map<number, number>> {
308 return {
309 preMap: (data: T) => {
310 const value = valueExtractor(data)
311 const frequencyMap = new Map<number, number>()
312 frequencyMap.set(value, 1)
313 return frequencyMap
314 },
315 reduce: (values: Array<[Map<number, number>, number]>) => {
316 // Combine all frequency maps
317 const combinedMap = new Map<number, number>()
318​
319 for (const [frequencyMap, multiplicity] of values) {
320 for (const [value, frequencyCount] of frequencyMap.entries()) {
321 const currentCount = combinedMap.get(value) || 0
322 combinedMap.set(value, currentCount + frequencyCount * multiplicity)
323 }
324 }
325​
326 return combinedMap
327 },
328 postMap: (result: Map<number, number>) => {
329 if (result.size === 0) return 0
330​
331 let modeValue = 0
332 let maxFrequency = 0
333​
334 for (const [value, frequency] of result.entries()) {
335 if (frequency > maxFrequency) {
336 maxFrequency = frequency
337 modeValue = value
338 }
339 }
340​
341 return modeValue
342 },
343 }
345​
346export const groupByOperators = {
347 sum,
348 count,
349 avg,
350 min,
351 max,
352 median,
353 mode,