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