27 lines
576 B
JavaScript
27 lines
576 B
JavaScript
// Simple moving average.
|
|
export class SimpleMovingAverage {
|
|
|
|
constructor(sampleCount = 10) {
|
|
this.sampleCount = sampleCount;
|
|
this.samples = [];
|
|
this.value = 0;
|
|
}
|
|
|
|
sample(datum) {
|
|
this.samples.push(datum);
|
|
if (this.samples.length > this.sampleCount) {
|
|
this.samples.splice(0, 1);
|
|
}
|
|
let sum = 0;
|
|
for (let i = 0; i < this.samples.length; i++) {
|
|
sum += this.samples[i];
|
|
}
|
|
const length = this.samples.length < this.sampleCount ?
|
|
this.samples.length
|
|
:
|
|
this.sampleCount;
|
|
this.value = sum / length;
|
|
}
|
|
|
|
}
|