Skip to content

Instantly share code, notes, and snippets.

@Gergling
Last active March 23, 2025 14:32
Show Gist options
  • Save Gergling/ced247ca176eb2ac39fe2b68a545185b to your computer and use it in GitHub Desktop.
Save Gergling/ced247ca176eb2ac39fe2b68a545185b to your computer and use it in GitHub Desktop.
A simple aggregation function for handling lists of data.
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