Clamp
VerifiedRestricts a number to an inclusive minimum and maximum.
- number
- range
- bounds
Install
npx shadcn@latest add https://quicksnip.dev/r/clamp.jsonCode
/** Restricts a number to the inclusive range [min, max]. */
export function clamp(value: number, min: number, max: number): number {
if (min > max) throw new RangeError("min must be less than or equal to max");
return Math.min(Math.max(value, min), max);
}Usage
clamp(15, 0, 10); // 10
clamp(-5, 0, 10); // 0