Clamp number

JavaScript, Math · Oct 22, 2020

Clamps num within the inclusive range specified by the boundary values a and b.

  • If num falls within the range, return num.
  • Otherwise, return the nearest number in the range.
const clampNumber = (num, a, b) =>
  Math.max(Math.min(num, Math.max(a, b)), Math.min(a, b));
clampNumber(2, 3, 5); // 3
clampNumber(1, -1, -5); // -1

More like this

  • Sum of powers in range

    Calculates the sum of the powers of all the numbers from start to end (both inclusive).

    JavaScript, Math · Oct 22, 2020

  • Geometric progression

    Initializes an array containing the numbers in the specified geometric progression range.

    JavaScript, Math · Dec 28, 2020

  • Random number in range

    Generates a random number in the specified range.

    JavaScript, Math · Oct 22, 2020