Open History to see the last commit
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
11}
12
13type PipedAggregateFunction<T, R> = {
14 pipe: (stream: IStreamBuilder<T>) => IStreamBuilder<KeyValue<string, R>>
15}
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]>
26}
27
28function isPipedAggregateFunction<T, R>(
29 aggregate: AggregateFunction<T, R>
30): aggregate is PipedAggregateFunction<T, R> {
31 return `pipe` in aggregate
32}
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 }
145}
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 }
163}
164
165/**
166 * Creates a count aggregate function
167 */
168export function count<T>(
169 valueExtractor: (value: T) => any = (v) => v
170): AggregateFunction<T, number, number> {
171 return {
172 // Count only not-null values (the `== null` comparison gives true for both null and undefined)
173 preMap: (data: T) => (valueExtractor(data) == null ? 0 : 1),
174 reduce: (values: Array<[number, number]>) => {
175 let totalCount = 0
176 for (const [nullMultiplier, multiplicity] of values) {
177 totalCount += nullMultiplier * multiplicity
178 }
179 return totalCount
180 },
181 }
182}
183
184/**
185 * Creates an average aggregate function
186 */
187export function avg<T>(
188 valueExtractor: (value: T) => number = (v) => v as unknown as number
189): AggregateFunction<T, number, { sum: number; count: number }> {
190 return {
191 preMap: (data: T) => ({
192 sum: valueExtractor(data),
193 count: 0,
194 }),
195 reduce: (values: Array<[{ sum: number; count: number }, number]>) => {
196 let totalSum = 0
197 let totalCount = 0
198 for (const [value, multiplicity] of values) {
199 totalSum += value.sum * multiplicity
200 totalCount += multiplicity
201 }
202 return {
203 sum: totalSum,
204 count: totalCount,
205 }
206 },
207 postMap: (result: { sum: number; count: number }) => {
208 return result.sum / result.count
209 },
210 }
211}
212
213type CanMinMax = number | Date | bigint
214
215/**
216 * Creates a min aggregate function that computes the minimum value in a group
217 * @param valueExtractor Function to extract a comparable value from each data entry
218 */
219export function min<T extends CanMinMax>(): AggregateFunction<
220 T,
221 T | undefined,
222 T | undefined
223>
224export function min<T, V extends CanMinMax>(
225 valueExtractor: (value: T) => V
226): AggregateFunction<T, V | undefined, V | undefined>
227export function min<T, V extends CanMinMax>(
228 valueExtractor?: (value: T) => V
229): AggregateFunction<T, V | undefined, V | undefined> {
230 const extractor = valueExtractor ?? ((v: T) => v as unknown as V)
231 return {
232 preMap: (data: T) => extractor(data),
233 reduce: (values) => {
234 let minValue: V | undefined
235 for (const [value, _multiplicity] of values) {
236 if (!minValue || (value && value < minValue)) {
237 minValue = value
238 }
239 }
240 return minValue
241 },
242 }
243}
244
245/**
246 * Creates a max aggregate function that computes the maximum value in a group
247 * @param valueExtractor Function to extract a comparable value from each data entry
248 */
249export function max<T extends CanMinMax>(): AggregateFunction<
250 T,
251 T | undefined,
252 T | undefined
253>
254export function max<T, V extends CanMinMax>(
255 valueExtractor: (value: T) => V
256): AggregateFunction<T, V | undefined, V | undefined>
257export function max<T, V extends CanMinMax>(
258 valueExtractor?: (value: T) => V
259): AggregateFunction<T, V | undefined, V | undefined> {
260 const extractor = valueExtractor ?? ((v: T) => v as unknown as V)
261 return {
262 preMap: (data: T) => extractor(data),
263 reduce: (values) => {
264 let maxValue: V | undefined
265 for (const [value, _multiplicity] of values) {
266 if (!maxValue || (value && value > maxValue)) {
267 maxValue = value
268 }
269 }
270 return maxValue
271 },
272 }
273}
274
275/**
276 * Creates a median aggregate function that computes the middle value in a sorted group
277 * If there's an even number of values, returns the average of the two middle values
278 * @param valueExtractor Function to extract a numeric value from each data entry
279 */
280export function median<T>(
281 valueExtractor: (value: T) => number = (v) => v as unknown as number
282): AggregateFunction<T, number, Array<number>> {
283 return {
284 preMap: (data: T) => [valueExtractor(data)],
285 reduce: (values: Array<[Array<number>, number]>) => {
286 // Flatten all values, taking multiplicity into account
287 const allValues: Array<number> = []
288 for (const [valueArray, multiplicity] of values) {
289 for (const value of valueArray) {
290 // Add each value multiple times based on multiplicity
291 for (let i = 0; i < multiplicity; i++) {
292 allValues.push(value)
293 }
294 }
295 }
296
297 // Return empty array if no values
298 if (allValues.length === 0) {
299 return []
300 }
301
302 // Sort values
303 allValues.sort((a, b) => a - b)
304
305 return allValues
306 },
307 postMap: (result: Array<number>) => {
308 if (result.length === 0) return 0
309
310 const mid = Math.floor(result.length / 2)
311
312 // If even number of values, average the two middle values
313 if (result.length % 2 === 0) {
314 return (result[mid - 1]! + result[mid]!) / 2
315 }
316
317 // If odd number of values, return the middle value
318 return result[mid]!
319 },
320 }
321}
322
323/**
324 * Creates a mode aggregate function that computes the most frequent value in a group
325 * If multiple values have the same highest frequency, returns the first one encountered
326 * @param valueExtractor Function to extract a value from each data entry
327 */
328export function mode<T>(
329 valueExtractor: (value: T) => number = (v) => v as unknown as number
330): AggregateFunction<T, number, Map<number, number>> {
331 return {
332 preMap: (data: T) => {
333 const value = valueExtractor(data)
334 const frequencyMap = new Map<number, number>()
335 frequencyMap.set(value, 1)
336 return frequencyMap
337 },
338 reduce: (values: Array<[Map<number, number>, number]>) => {
339 // Combine all frequency maps
340 const combinedMap = new Map<number, number>()
341
342 for (const [frequencyMap, multiplicity] of values) {
343 for (const [value, frequencyCount] of frequencyMap.entries()) {
344 const currentCount = combinedMap.get(value) || 0
345 combinedMap.set(value, currentCount + frequencyCount * multiplicity)
346 }
347 }
348
349 return combinedMap
350 },
351 postMap: (result: Map<number, number>) => {
352 if (result.size === 0) return 0
353
354 let modeValue = 0
355 let maxFrequency = 0
356
357 for (const [value, frequency] of result.entries()) {
358 if (frequency > maxFrequency) {
359 maxFrequency = frequency
360 modeValue = value
361 }
362 }
363
364 return modeValue
365 },
366 }
367}
368
369export const groupByOperators = {
370 sum,
371 count,
372 avg,
373 min,
374 max,
375 median,
376 mode,
377}