Created
May 27, 2016 22:27
-
-
Save huttj/34adf7504a1a53bc308d9262d83d3b4f to your computer and use it in GitHub Desktop.
This file contains hidden or 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 MovingAverage(size) { | |
this.buckets = []; | |
while (1 + size--) { | |
this.buckets.push(0); | |
} | |
this.i = 0; | |
this.average = 0; | |
} | |
MovingAverage.prototype.add = function add(n) { | |
this.average -= this.buckets[this.i] / this.buckets.length; | |
this.buckets[this.i] = n; | |
this.average += n / this.buckets.length; | |
this.i = this.i === this.buckets.length - 1 ? 0 : this.i + 1; | |
}; | |
var ma = new MovingAverage(100); | |
var limit = 1000; | |
var r = 0; | |
while (limit--) { | |
r = Math.floor(Math.random()*1000) - 500; | |
ma.add(r); | |
console.log(_Pad(ma.average.toFixed(2), 7), _Pad(r, 7)); | |
} | |
function _Pad(s, l) { | |
return leftPad(s, ' ', l); | |
} | |
function leftPad(str, char, len) { | |
str = ''+str; | |
char = ''+char; | |
while (str.length + char.length <= len) { | |
str = char + str; | |
} | |
return str; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment