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
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
python
import random from typing import Iterator, List
How reservoir sampling picks k items
reservoir-sampling
streaming
randomness
Intermediate
5 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
javascript
const SWIPE_THRESHOLD = 80; const MAX_TRANSLATE = 120; export function attachSwipeToDismiss(element, onDismiss) {
Building a swipe-to-dismiss gesture in JS
touch-events
gesture-detection
dom-manipulation
Intermediate
10 steps
javascript
const { pool } = require('./db'); function withTransaction() { return async (req, res, next) => {
A per-request transaction middleware in Express
middleware
database-transactions
connection-pooling
Advanced
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.