Last active
December 27, 2015 05:09
-
-
Save jsvine/7272248 to your computer and use it in GitHub Desktop.
Just a little helper function. Depends on, and hooks into, underscore.
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 () { | |
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