612 bytes · the TypeScript implementation · view raw
/** * Clamp `value` to the inclusive range `min..max`. * * Swapped bounds throw: `Math.max(min, Math.min(value, max))` would answer * `min` for everything and hide the bug that swapped them. */exportfunction clamp(value: number, min: number, max: number): number {
if (!Number.isInteger(value) || !Number.isInteger(min) || !Number.isInteger(max)) {
thrownew TypeError("clamp operates on integers only");
}
if (min > max) {
thrownew RangeError(`min must not be greater than max (min ${min}, max ${max})`);
}
if (value < min) return min;
if (value > max) return max;
return value;
}