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