UNPKG

@naturalcycles/js-lib

Version:

Standard library for universal (browser + Node.js) javascript

46 lines (45 loc) 1.01 kB
/** * Implements a Simple Moving Average algorithm. */ export class SimpleMovingAverage { size; data; constructor(size, data = []) { this.size = size; this.data = data; } /** * Next index of array to push to */ nextIndex = 0; /** * Current average (calculated on the fly). * Returns 0 (not undefined) for empty data. */ get avg() { if (this.data.length === 0) return 0; let total = 0; for (const n of this.data) total += n; return total / this.data.length; } /** * Push new value. * Returns newly calculated average (using newly pushed value). */ pushGetAvg(n) { this.push(n); return this.avg; } /** * Push new value. */ push(n) { this.data[this.nextIndex] = n; this.nextIndex = this.nextIndex === this.size - 1 ? 0 // reset : this.nextIndex + 1; } }