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