Last active
April 27, 2017 17:04
-
-
Save FergusInLondon/dcc340dc9edcd8ef8ea196512ca53afe to your computer and use it in GitHub Desktop.
Simple Rolling Average function
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
/* Fergus In London - https://fergus.london - <[email protected]> | |
* | |
* Simple little function for calculating rolling averages, both simple and | |
* weighted. Example can be found on the GitHub Gist, or on my website. | |
* | |
* Do as you please, no rights reserved and no warranties provided. :) | |
*/ | |
/** | |
* Constructs a new "roller" function. | |
* | |
* @param Number Defaults to 10 | |
* @param Boolean Defaults to false | |
* @return Function | |
*/ | |
var roller = function(limit, weighted) { | |
// Initialise Defaults | |
limit = limit || 10; | |
weighted = weighted || false; | |
// Instance Variables | |
var points = []; | |
// Calculates an Average; either weighted (linear) or standard. | |
function calculateAverage() { | |
return (function(sum, data, n){ | |
/* Sum of Consecutive Integers */ | |
var weightbase = (n * (n+1)) / 2; | |
for(var i = 0; i < n; i++) | |
sum += (weighted) ? data[i] * ((i+1) / weightbase) : data[i]; | |
return sum; | |
})(0, points, points.length) / ((weighted) ? 1 : points.length); | |
}; | |
/** | |
* Adds the value to the internal list, ensuring the list adheres to the | |
* confines defined by the user during construction, and then returns the | |
* average. | |
* | |
* @param Number | |
* @return Number|NaN | |
*/ | |
return function(val) { | |
if (isNaN(val)) return NaN; | |
points.push(val); | |
if( points.length > limit ) points.shift(); | |
return calculateAverage(); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example Usage
Simple Rolling Average
Weighted Rolling Average