UNPKG

als-statistics

Version:

A powerful and lightweight JavaScript library for descriptive statistics, regression, clustering, outlier detection, and noise analysis using a flexible table/column architecture.

30 lines (27 loc) 1.2 kB
class MovingAverage { constructor(sample, windowSize,sampleThreshold = 1000) { this.sample = sample this.windowSize = windowSize if (!Number.isInteger(windowSize) || windowSize < 1) throw new Error("windowSize must be a positive integer"); if (windowSize > sample.n) throw new Error('window size cant be bigger than sample size') this.result = [] sample.n > sampleThreshold ? this.bigSample() : this.naiveSample() } bigSample() { const { sample: { values, n }, windowSize,result } = this const prefixSums = new Array(n + 1).fill(0); for (let i = 0; i < n; i++) { prefixSums[i + 1] = prefixSums[i] + values[i] } for (let i = 0; i + windowSize <= n; i++) { result.push((prefixSums[i + windowSize] - prefixSums[i]) / windowSize); } } naiveSample() { const { sample: { values, n }, windowSize,result } = this for (let start = 0; start + windowSize <= n; start++) { let sumWindow = 0; for (let i = start; i < start + windowSize; i++) { sumWindow += values[i] } result.push(sumWindow / windowSize); } } } module.exports = MovingAverage