Skip to content

Instantly share code, notes, and snippets.

@zootella
Created March 4, 2013 22:18
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 zootella/5086203 to your computer and use it in GitHub Desktop.
Save zootella/5086203 to your computer and use it in GitHub Desktop.
// Calculate the average of a number of values as they are produced
var newAverage = function() {
var o = {};
var n = 0; o.n = function() { return n; } // How many values we have, 0 before you add one
var total = 0; o.total = function() { return total; } // The total sum of all the given values
var minimum = 0; o.minimum = function() { return minimum; } // The smallest value we have seen, 0 before we have any values
var maximum = 0; o.maximum = function() { return maximum; } // The largest value we have seen, 0 before we have any values
var recent = 0; o.recent = function() { return recent; } // The most recent value you added, 0 before we have any values
// Record a new value to make it a part of this average
o.add = function(value) {
n++; // Count another value
total += value; // Add the value to our total
if (n === 1 || value < minimum) minimum = value; // First or smallest value
if (n === 1 || value > maximum) maximum = value; // First or largest value
recent = value; // Remember the most recent value
},
// The current average, 0 before we have any values
o.average = function() {
if (n === 0) return 0;
return total / n;
},
// The current average in thousandths, given 4, 5, and 6, the average is 5000
o.averageThousandths = function() { return averageMultiply(1000); },
// The current average multiplied by the given number
o.averageMultiply = function(multiply) {
if (n === 0) return 0;
return multiply * total / n;
},
// Text that describes the current average, like "5.000", "Undefined" before we have any values
o.say = function() {
if (n === 0) return 'Undefined';
return describe.decimal(averageThousandths(), 3);
};
return o;
};
var a = newAverage();
a.add(4);
a.add(5);
a.add(6);
console.log(a.say());//5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment