Skip to content
GreenSnippets

Clamp, lerp and map a number range

Small numeric helpers for sliders, animations and progress bars.

JavaScript
const clamp = (value, min, max) => Math.min(Math.max(value, min), max);

const lerp = (start, end, t) => start + (end - start) * t;

const mapRange = (value, inMin, inMax, outMin, outMax) =>
  inMin === inMax ? outMin : outMin + ((value - inMin) / (inMax - inMin)) * (outMax - outMin);

Example / expected output

Output
clamp(15, 0, 10)               // 10
lerp(0, 100, 0.25)             // 25
mapRange(512, 0, 1023, 0, 100) // about 50.05

How it works

clamp keeps a value inside a range, lerp blends linearly between two values, and mapRange converts a value from one scale to another, for example 0–1023 sensor readings to 0–100%.