Created
November 14, 2017 23:05
-
-
Save hn3000/9834742b33cd3ce265ea4203ae58bcc4 to your computer and use it in GitHub Desktop.
(pretty) generic aggregation / grouping function using reduce
This file contains 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
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