Let's build a utility function
today! We will be focusing on a clamp
utilty, which keeps a number set within predefined bounds.
First, lets think about what this utility function
should do.
- It should accept a
number
which we want toclamp
- It should take a
min
andmax
value toclamp
our first input to - It should return a
number
thats been clamped
function clamp(value, min, max) { return Math.max(min, Math.min(max, value)); } console.log(clamp(10, 0, 5)); // 5 console.log(clamp(-10, 0, 5)); // 0 console.log(clamp(5, 0, 10)); // 5
Console:
This is all the logic we will need to be able to clamp
a number
. And before we get overwhelmed by all of the min/max stuff going on there, let's break this down into smaller chunks.
function clamp(value, min, max) { // return Math.max(min, Math.min(max, value)); }
First off, we create the clamp
function
and it accepts thre arguments
value
- the number that we want toclamp
min
- the lower bound of theclamp
max
- the upper bound of theclamp
Now for the real part of the logic.
We have to different Math
methods being use here, let's look at the inner Math.min
first.
Math.min(max, value)
With this logic we are trying to find the minimum value between the max
and value
. If thevalue
is smaller than the max
value, we return the value
because it's smaller. Otherwise, if the value
is larger than the max value, we return the
max value, because its the smaller value of the two.
So now That we can keep the value
within the max
bounds, let's now take a look at the min
logic.
Math.max(min, maxValue)
This is almost the exact same logic as the max
bound logic we just wrote. To keep the value
within the lower bound, we find the max value between our lower bound and the maxValue
we found previously.
So to wrap it up, to clamp a number, we first find the minimum between max
and value
. Then we find the maximum between the min
and maxValue
. Easy Peasy! Now get out there and and start clamping some numbers!