Clamp, lerp and map a number range
Small numeric helpers for sliders, animations and progress bars.
- JavaScript
- GreenSnippets
- MIT
- Executed with Node.js 22
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
clamp(15, 0, 10) // 10
lerp(0, 100, 0.25) // 25
mapRange(512, 0, 1023, 0, 100) // about 50.05How 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%.
Related snippets
- JavaScript Tested
Remove duplicates from an array
Deduplicate primitives with a Set, or objects by a key or computed value, keeping the first occurrence.
- JavaScript Tested
Truncate a string with an ellipsis
Shorten text to a maximum length without cutting in the middle of a word or a Unicode character.
- JavaScript Tested
Sort an array by multiple keys
Sort objects by one field, then break ties with another, with ascending or descending order per field.
- JavaScript Tested
Slugify a string for URLs
Convert any title into a lowercase, hyphenated, accent-free slug that is safe to use in a URL.

