From 9e620d41c4a96b86424b1cd232730fb5a1a80d5a Mon Sep 17 00:00:00 2001 From: Xavey Aguarez Date: Wed, 27 Dec 2017 01:55:32 -0800 Subject: [PATCH] tightened code for clampnumber clampNumber is now a single line function --- snippets/clampNumber.md | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/snippets/clampNumber.md b/snippets/clampNumber.md index a71e4136e..0bb2635eb 100644 --- a/snippets/clampNumber.md +++ b/snippets/clampNumber.md @@ -1,16 +1,13 @@ ### clampNumber -Clamps `num` within the inclusive `lower` and `upper` bounds. +Clamps `num` within the inclusive range specified by the boundary values `a` and `b` -If `lower` is greater than `upper`, swap them. If `num` falls within the range, return `num`. Otherwise, return the nearest number in the range. ```js -const clampNumber = (num, lower, upper) => { - if (lower > upper) upper = [lower, lower = upper][0]; - return (num >= lower && num <= upper) ? num : ((num < lower) ? lower : upper); -}; +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 // clampNumber(3, 2, 4) -> 3