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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Tracking a running sum turns each update into O(1) work instead of re-summing the window.
- 2A circular buffer with a modulo head reuses fixed memory while overwriting the oldest entry.
- 3Async generators let you transform a stream lazily, one item at a time, without buffering everything.
Related explainers
javascript
import { useReducer, useCallback } from 'react'; function historyReducer(state, action) { const { past, present, future } = state;
Undo/redo form state with a React reducer
undo-redo
reducer
immutability
Intermediate
10 steps
python
import hashlib from collections import defaultdict from pathlib import Path
Finding duplicate files by size then hash
hashing
file-io
deduplication
Intermediate
7 steps
javascript
import { NextResponse } from 'next/server'; import { db } from '@/lib/db'; function csvCell(value) {
Streaming a CSV export in a Next.js route
streaming
csv
readablestream
Advanced
9 steps
go
package metrics import ( "sync"
A thread-safe sliding-window average in Go
concurrency
sliding-window
running-average
Intermediate
8 steps
javascript
const { Pool } = require('pg'); const pool = new Pool({ connectionString: process.env.DATABASE_URL,
Per-request Postgres connections in Express
connection-pooling
middleware
transactions
Intermediate
8 steps
javascript
const express = require('express'); const router = express.Router(); const db = require('../db');
Building a paginated orders page in Express
pagination
routing
sql-queries
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-rolling-average-over-a-fixed-window-explained-javascript-6fb5/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.