29 lines
548 B
JavaScript
29 lines
548 B
JavaScript
|
|
/**
|
|
* A moving average computation
|
|
*/
|
|
export class MovingAverage {
|
|
constructor(windowSize) {
|
|
this._windowSize = windowSize;
|
|
this._queue = [];
|
|
this._queueSum = 0;
|
|
}
|
|
|
|
windowSize() {
|
|
return this._windowSize;
|
|
}
|
|
|
|
addVector(vec) {
|
|
return vec.map(this.add.bind(this));
|
|
}
|
|
|
|
add(value) {
|
|
this._queueSum += value;
|
|
this._queue.push(value);
|
|
if(this._queue.length > this._windowSize) {
|
|
this._queueSum -= this._queue[0];
|
|
this._queue.shift();
|
|
}
|
|
return this._queueSum / this._queue.length;
|
|
}
|
|
}; |