Skip to content

Instantly share code, notes, and snippets.

@FergusInLondon
Last active April 27, 2017 17:04
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 FergusInLondon/dcc340dc9edcd8ef8ea196512ca53afe to your computer and use it in GitHub Desktop.
Save FergusInLondon/dcc340dc9edcd8ef8ea196512ca53afe to your computer and use it in GitHub Desktop.
Simple Rolling Average function
/* Fergus In London - https://fergus.london - <fergus@fergus.london>
*
* 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();
};
};
@FergusInLondon
Copy link
Author

FergusInLondon commented Apr 27, 2017

Example Usage

Simple Rolling Average

var rolling = roller(5),
    tests = [
  // IN   OUT 
  [  6  ,  6  ],
  [  3  , 4.5 ],
  [  1  , 3.3 ],
  [  10 ,  5  ],
  [  5  ,  5  ],
  [  7  , 5.2 ]
];

tests.forEach(function(test){
  var result = rolling(test[0]);
  console.log("Input: "+ test[0] +". Output: "+ result);

  if (result.toFixed(1) != test[1])
    throw "Incorrect Value Returned! (Expected "+ test[1] +")";
});

Weighted Rolling Average

var rolling = roller(5, true), result = 0;

[77, 79, 79, 81, 83].forEach(function(num){
   result = rolling(num);
});

console.log("Weighted Rolling Average: "+ result);
if (result.toFixed(2) != 80.73)
  throw "Incorrected Value Returned! (Expected 80.73)";

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment