Moving Average With a Fixed Window
Calculate a simple moving average over a fixed window with a rolling sum, validating window size and numeric values.
Code
export function movingAverage(values: readonly number[], window: number): number[] {
if (!Array.isArray(values) || values.length === 0) {
throw new RangeError("values must be a non-empty array");
}
if (!Number.isInteger(window) || window < 1 || window > values.length) {
throw new RangeError("window must be an integer between 1 and values.length");
}
if (!values.every(Number.isFinite)) {
throw new TypeError("values must be finite numbers");
}
const result: number[] = [];
let sum = 0;
for (let index = 0; index < values.length; index += 1) {
sum += values[index];
if (index >= window) sum -= values[index - window];
if (index >= window - 1) result.push(sum / window);
}
return result;
}Inside the snippet
Moving Average With a Fixed Window is built around the function movingAverage.
Repetition is confined to for (let index = 0; index < values.length; index += 1) — the rest of the file is straight-line. A guard precedes the RangeError and TypeError: bad state stops the flow there instead of continuing.
What to watch for
- The snippet leans on
window— browser-only surfaces a bare Node process cannot provide.
Putting it to use
The main signature reads export function movingAverage(values: readonly number[], window: number)
Import movingAverage from the file and call it — the rest of the code is implementation detail.
Core lines
throw new RangeError("window must be an integer between 1 and values.length");
throw new RangeError("values must be a non-empty array");
for (let index = 0; index < values.length; index += 1) {
sum += values[index];
if (index >= window) sum -= values[index - window];
if (index >= window - 1) result.push(sum / window);
}
Interactive Tools for This Topic
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Statistics CalculatorCompute count, sum, mean, median, minimum, maximum, range, variance, and standard deviation for a number list.
FAQ
- What happens on invalid input?
- It throws `RangeError` and `TypeError` before any real work runs — handle it at the call site or let it propagate deliberately.
- Does Moving Average With a Fixed Window run in plain Node.js?
- No — it touches `window`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.