Created
March 4, 2013 22:18
-
-
Save zootella/5086203 to your computer and use it in GitHub Desktop.
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
// 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