Last active
August 29, 2015 14:06
-
-
Save gilbert/885b39f47d1f6f8c07c0 to your computer and use it in GitHub Desktop.
// source http://jsbin.com/leseha/2
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
var myData = [ | |
{ | |
week: 1, | |
count: 5 | |
}, | |
{ | |
week: 2, | |
count: 1 | |
}, | |
{ | |
week: 1, | |
count: 1 | |
}, | |
{ | |
week: 2, | |
count: 3 | |
}, | |
{ | |
week: 2, | |
count: 4 | |
} | |
]; | |
//----Helper debugger------------------------- | |
var log = function (x,y,z) { | |
console.log("eh?",x,y,z); | |
return x; | |
}; | |
//----Useful utility functions---------------- | |
var compose = function (f, g) { | |
return function (x) { return f( g(x) ); }; | |
}; | |
//----JS-tailored function-------------------- | |
var uniqueFilter = function (item, index, array) { | |
return array.indexOf(item) === index; | |
}; | |
//----Ahh, real functions!-------------------- | |
var prop = function (propName) { | |
return function (obj) { return obj[propName]; }; | |
}; | |
var compare = function (value) { | |
return function (target) { return target === value; }; | |
}; | |
var add = function (x, y) { return x + y; }; | |
var uniqueValues = function (objArray, key) { | |
return objArray.map( prop(key) ).filter(uniqueFilter); | |
}; | |
//----The meat and potatos-------------------- | |
function reduceByKey(data, key, value) { | |
return uniqueValues(data, key) | |
.map(function(uniqVal) { | |
var sum = data | |
.filter( compose(compare(uniqVal), prop(key)) ) | |
.map( prop(value) ) | |
.reduce(add) | |
; | |
return { | |
key: uniqVal, | |
value: sum | |
}; | |
}) | |
; | |
} | |
var x = reduceByKey(myData, 'week', 'count'); | |
console.log(x); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment