Skip to content

Instantly share code, notes, and snippets.

@jsvine
Last active December 27, 2015 05:09
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 jsvine/7272248 to your computer and use it in GitHub Desktop.
Save jsvine/7272248 to your computer and use it in GitHub Desktop.
Just a little helper function. Depends on, and hooks into, underscore.
(function () {
var root = this;
var sum = function (arr) {
return _.reduce(arr, function (m, x) {
return m + x;
});
};
// n: Size of the stack, i.e., how far to look back
var rollingAverage = function (arr, n) {
var stack = [];
return _.map(arr, function (item) {
stack.push(item);
if (stack.length > n) { stack.shift(); }
return sum(stack) / stack.length;
});
};
root._.rollingAverage = rollingAverage;
}).call(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment