typescript
36 lines · 6 steps
A weighted moving average in TypeScript
Smooth a series of timestamped readings by averaging each point with its recent neighbors, giving newer samples more weight.
Explained by
highlit
1interface Reading {
2 timestamp: number;
3 value: number;
4}
5
6export function weightedMovingAverage(
7 readings: readonly Reading[],
8 windowSize: number,
9): Reading[] {
10 if (windowSize < 1) {
11 throw new RangeError(`windowSize must be >= 1, got ${windowSize}`);
12 }
13
14 const smoothed: Reading[] = [];
15
16 for (let i = 0; i < readings.length; i++) {
17 const start = Math.max(0, i - windowSize + 1);
18 const window = readings.slice(start, i + 1);
19
20 let weightedSum = 0;
21 let weightTotal = 0;
22
23 window.forEach((reading, offset) => {
24 const weight = offset + 1;
25 weightedSum += reading.value * weight;
26 weightTotal += weight;
27 });
28
29 smoothed.push({
30 timestamp: readings[i].timestamp,
31 value: weightedSum / weightTotal,
32 });
33 }
34
35 return smoothed;
36}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A sliding window that grows from the array start avoids special-casing the first few elements.
- 2Linear weights let recent samples dominate without discarding older context entirely.
- 3Validating inputs up front turns silent nonsense into a clear, actionable error.
Related explainers
typescript
import { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; import localeFrExtra from '@angular/common/locales/extra/fr'; import localeDe from '@angular/common/locales/de';
Locale-aware bootstrapping in Angular
i18n
localization
dependency-injection
Intermediate
8 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { InjectRepository } from '@nestjs/typeorm';
A cache-aside country lookup in NestJS
cache-aside
dependency-injection
batch-lookup
Intermediate
8 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core'; interface Preferences { theme: 'light' | 'dark';
A signal-based preferences store in Angular
signals
state-management
persistence
Intermediate
7 steps
typescript
import { useEffect, useState } from "react"; interface Section { id: string;
Building a scroll-spy hook in React
custom-hooks
intersectionobserver
dom-observation
Intermediate
8 steps
typescript
import { Injectable, Scope, Inject, NotFoundException } from '@nestjs/common'; import { REQUEST } from '@nestjs/core'; import { Request } from 'express'; import { DataSource } from 'typeorm';
Per-tenant database connections in NestJS
multi-tenancy
connection-pooling
dependency-injection
Advanced
8 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-weighted-moving-average-in-typescript-explained-typescript-b8a6/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.