Files
30-seconds-of-code/snippets/clamp-number.md
Angelos Chalaris 61200d90c4 Kebab file names
2023-04-27 21:58:35 +03:00

502 B

title, tags, cover, firstSeen, lastUpdated
title tags cover firstSeen lastUpdated
Clamp number math clay-pot-horizon 2017-12-20T19:19:18+02:00 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