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