ClampLoading saved progress…

Clamp

Implement clamp(number, lower, upper) — constrain number so it never leaves the inclusive range [lower, upper]. If the number is smaller than lower, you return lower; if it is larger than upper, you return upper; otherwise you hand back the number untouched. Think of a volume knob that physically cannot turn past 0 or past 100 — values outside the range get pinned to the nearest edge. This mirrors Lodash's _.clamp.

Signature

// number: number   — the value to constrain.
// lower:  number    — the inclusive minimum; results never go below this.
// upper:  number    — the inclusive maximum; results never go above this.
// returns: number   — number itself if it is inside [lower, upper],
//                     otherwise whichever bound it crossed.
function clamp(number, lower, upper): number;

Examples

// Above the upper bound: pulled down to the maximum.
clamp(10, 0, 5);
// → 5
// Below the lower bound: pushed up to the minimum.
clamp(-10, 0, 5);
// → 0

// Already inside the range: returned unchanged.
clamp(3, 0, 5);
// → 3

Notes

  • The range is inclusive. A number exactly equal to lower or upper is inside the range, so it comes back unchanged — clamp(5, 0, 5) is 5, not anything else.
  • Bounds can be negative. clamp(-5, -3, 3) returns -3. Nothing about the logic assumes the bounds are positive.
  • Floats are fine. The function does no rounding — clamp(0.25, 0, 1) returns 0.25, and clamp(2.5, 0, 1) returns 1.
  • You may assume all three arguments are numbers. You do not need to handle missing arguments, NaN, or a lower greater than upper.
  • Return, don't mutate. There is nothing to mutate here — just compute and return the constrained value.
Loading editor…