typescript 44 lines · 8 steps

Interpolating a color gradient in TypeScript

Map a number to a smooth color by linearly blending between fixed RGB stops.

Explained by highlit
1type RGB = readonly [number, number, number];
2 
3interface ColorStop {
4 offset: number;
5 color: RGB;
6}
7 
8const HEATMAP_STOPS: ColorStop[] = [
9 { offset: 0.0, color: [33, 102, 172] },
10 { offset: 0.25, color: [103, 169, 207] },
11 { offset: 0.5, color: [247, 247, 247] },
12 { offset: 0.75, color: [239, 138, 98] },
13 { offset: 1.0, color: [178, 24, 43] },
14];
15 
16const clamp01 = (n: number): number => Math.min(1, Math.max(0, n));
17 
18const lerp = (a: number, b: number, t: number): number => a + (b - a) * t;
19 
20function interpolateGradient(t: number, stops: ColorStop[] = HEATMAP_STOPS): RGB {
21 const clamped = clamp01(t);
22 
23 let upper = stops.findIndex((stop) => stop.offset >= clamped);
24 if (upper <= 0) {
25 return upper === 0 ? stops[0].color : stops[stops.length - 1].color;
26 }
27 
28 const lower = stops[upper - 1];
29 const next = stops[upper];
30 const span = next.offset - lower.offset;
31 const local = span === 0 ? 0 : (clamped - lower.offset) / span;
32 
33 return [
34 Math.round(lerp(lower.color[0], next.color[0], local)),
35 Math.round(lerp(lower.color[1], next.color[1], local)),
36 Math.round(lerp(lower.color[2], next.color[2], local)),
37 ];
38}
39 
40export function heatmapCellColor(value: number, min: number, max: number): string {
41 const normalized = max === min ? 0.5 : (value - min) / (max - min);
42 const [r, g, b] = interpolateGradient(normalized);
43 return `rgb(${r}, ${g}, ${b})`;
44}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Linear interpolation between sorted stops turns a scalar into a continuous color scale.
  2. 2Clamping and edge-case guards keep out-of-range or degenerate inputs from breaking the math.
  3. 3A small readonly tuple type makes the RGB contract explicit and hard to misuse.

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.

Interpolating a color gradient in TypeScript — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code