Skip to content

Instantly share code, notes, and snippets.

@surr-name
Last active September 6, 2016 10:21
Show Gist options
  • Save surr-name/b3c9039fa34ad35fdb1d1e2c5b722f94 to your computer and use it in GitHub Desktop.
Save surr-name/b3c9039fa34ad35fdb1d1e2c5b722f94 to your computer and use it in GitHub Desktop.
Moving Average
function Constr ( length ) {
if ( typeof length !== 'number' ) throw(
SyntaxError('length must be a Number')
);
this.length = length;
this._length = length - 1;
this._bin = new Array(this.length);
this._pointer = -1;
this._sum = 0;
this.am;
this._filled = false;
}
Constr.prototype.next = function ( value ) {
value = value * 1;
this._pointer++;
this._sum += -( this._bin[this._pointer] || 0) + value;
this._bin[this._pointer] = value;
if ( this._pointer === this._length ) {
this._filled = true;
this._pointer = -1;
}
if ( this._filled ) return this.am = this._sum / this.length;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment