Files
30-seconds-of-code/javascript/snippets/clamp-number.md
2023-05-01 22:35:56 +03:00

482 B

title, type, tags, cover, dateModified
title type tags cover dateModified
Clamp number snippet
math
clay-pot-horizon 2020-10-22T20:23:47+03:00

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