javascript 40 lines · 7 steps

A rolling average over a fixed window

A circular buffer computes a moving average in constant time per reading, then streams it over async data.

Explained by highlit
1class MovingAverage {
2 constructor(windowSize) {
3 if (!Number.isInteger(windowSize) || windowSize <= 0) {
4 throw new RangeError('windowSize must be a positive integer');
5 }
6 this.windowSize = windowSize;
7 this.buffer = new Float64Array(windowSize);
8 this.count = 0;
9 this.head = 0;
10 this.sum = 0;
11 }
12 
13 push(reading) {
14 const value = Number(reading);
15 if (!Number.isFinite(value)) return this.average();
16 
17 if (this.count === this.windowSize) {
18 this.sum -= this.buffer[this.head];
19 } else {
20 this.count += 1;
21 }
22 
23 this.buffer[this.head] = value;
24 this.sum += value;
25 this.head = (this.head + 1) % this.windowSize;
26 
27 return this.average();
28 }
29 
30 average() {
31 return this.count === 0 ? NaN : this.sum / this.count;
32 }
33}
34 
35async function* smoothedReadings(source, windowSize) {
36 const avg = new MovingAverage(windowSize);
37 for await (const { timestamp, value } of source) {
38 yield { timestamp, raw: value, smoothed: avg.push(value) };
39 }
40}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Tracking a running sum turns each update into O(1) work instead of re-summing the window.
  2. 2A circular buffer with a modulo head reuses fixed memory while overwriting the oldest entry.
  3. 3Async generators let you transform a stream lazily, one item at a time, without buffering everything.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A rolling average over a fixed window — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code