Skip to content

Instantly share code, notes, and snippets.

@hn3000
Created November 14, 2017 23:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hn3000/9834742b33cd3ce265ea4203ae58bcc4 to your computer and use it in GitHub Desktop.
Save hn3000/9834742b33cd3ce265ea4203ae58bcc4 to your computer and use it in GitHub Desktop.
(pretty) generic aggregation / grouping function using reduce
function aggregate<I, V>(
items: I[],
valueFun: (i: I) => V,
groupingFun: (i: I) => string,
combineFun: (v1: V, v2: V) => V
): ({ [g:string]: V }) {
return items.reduce(
(r: { [g: string]: V }, i: I) => {
let g = groupingFun(i);
let v = valueFun(i);
r[g] = (r[g] != null) ? combineFun(v, r[g]) : v;
return r;
},
{}
);
}
// sum of even / odd numbers
console.log(aggregate(
[1, 2, 3, 4, 5, 6, 7, 8, 9],
v => v, v => '' + (v % 2), (u, v) => (u + v)
));
// sum of count by category
console.log(aggregate(
[
{ cat: 'a', value: 1 },
{ cat: 'a', value: 2 },
{ cat: 'b', value: 1 },
{ cat: 'b', value: 2 },
{ cat: 'b', value: 3 },
{ cat: 'c', value: 1 },
{ cat: 'b', value: 4 },
{ cat: 'a', value: 3 },
],
v => v.value, v => v.cat, (u, v) => (u + v)
));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment