Created
April 12, 2016 11:42
-
-
Save vwochnik/899ce8caf485a4f0d68ff6966fc6307d to your computer and use it in GitHub Desktop.
Aggregate dataset by ticks
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
/** | |
* Aggregates a dataset containing {x,y} values by an array of x-axis ticks | |
* where the aggregated dataset contains one {x,y} value per specified | |
* tick. | |
* @param dataset input dataset of {x,y} values | |
* @param ticks array of ticks to aggregate by | |
* @return new dataset containing aggregated {x,y} values | |
*/ | |
function aggregate(dataset, ticks) { | |
return _.chain(dataset) | |
.filter(function(data) { | |
return (data.x >= ticks[0] && data.x < ticks[ticks.length - 1]); | |
}) | |
.groupBy(function(data) { | |
for (var i = 0; i < ticks.length; i++) { | |
if (data.x < ticks[i]) { | |
return i - 1; | |
} | |
} | |
return ticks.length - 1; | |
}) | |
.map(function(group, i) { | |
return _.reduce(group, function(memo, data) { | |
memo.y += data.y; | |
return memo; | |
}, { x: ticks[i], y: 0 }); | |
}).value(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment