Last active
March 23, 2025 14:32
A simple aggregation function for handling lists of data.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type KeyGenerator<ItemProps> = (item: ItemProps) => string; | |
type Reducer<AggregatedProps, ItemProps> = ( | |
aggregation: AggregatedProps, | |
item: ItemProps, | |
idx: number, | |
) => AggregatedProps; | |
type Aggregation<AggregatedProps> = { | |
key: string; | |
items: ItemProps[]; | |
values: AggregatedProps; | |
}; | |
type AggregationMapping<AggregatedProps> = { | |
[key: string]: Aggregation; | |
}; | |
const getAggregation = <ItemProps, AggregatedProps>( | |
list: ItemProps[], | |
keyGenerator: KeyGenerator<ItemProps>, | |
reducer: Reducer<AggregatedProps, ItemProps>, | |
): Aggregation[] => { | |
const aggregationMapping: AggregationMapping<AggregatedProps> = {}; | |
list.forEach((item, idx) => { | |
const key = keyGenerator(item); | |
const aggregation = aggregationMapping[key] || { | |
key, | |
items: [], | |
values: {}, | |
}; | |
aggregationMapping[key] = { | |
...aggregation, | |
items: [...aggregation.items, item], | |
values: reducer(aggregation.values, item, idx), | |
}; | |
}); | |
return Object.values(aggregationMapping); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment