Functional Weave
Code in Rust

math.clamp@1.0.0

impl/typescript.ts

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.
 */
export function clamp(value: number, min: number, max: number): number {
  if (!Number.isInteger(value) || !Number.isInteger(min) || !Number.isInteger(max)) {
    throw new TypeError("clamp operates on integers only");
  }
  if (min > max) {
    throw new RangeError(`min must not be greater than max (min ${min}, max ${max})`);
  }
  if (value < min) return min;
  if (value > max) return max;
  return value;
}