Snippet

clamp()

edit
function clamp(min, max) {
  return num => Math.min(Math.max(min, num), max)
}

I have found this function useful again and again in my career, often serving as a way to prevent invalid number values where using HTML attributes of min and max are not sufficient.

It can take a moment to understand how clamp works because it’s a bit counterintuitive. We make use of Math.min and Math.max to accomplish clamp.

Math.min will return you the minimal value of a set of numbers.

console.log(Math.min(76, 24, -42)) // -42

Math.max will return to you the maximal value of a set of numbers.

console.log(Math.max(76, 24, -42)) // 76

Therefore, we can create a clamp by composing these together. First we make sure that the number is not below our min with:

const minThresholdResult = Math.max(min, number)

You can hopefully see that if number is less than min, Math.max will return min, therefore clamping the result to the min value. We pass this result into our next check, ensuring the value is not above max with:

const result = Math.min(minThresholdResult, max)

If the value of minThresholdResult is higher than our max value, it will clamp it to the max value of our range, otherwise it will return our value.

Here it is in use:

const between0and100 = clamp(0, 100)

const numbers = [42, 142, -42]

numbers.forEach(number => {
  console.log(between0and100(number))
})

// 42
// 100
// 0

Finished reading?
Liked the post? Give the author a dopamine boost with a few "beard strokes". Click the beard up to 50 times to show your appreciation.

Kyle Shevlin's face, which is mostly a beard with eyes
Kyle Shevlin is a software engineer who specializes in JavaScript, TypeScript, React and frontend web development.
Agathist
Good software by good people.
Visit https://agath.ist to learn more
Sign up for my newsletter
Let's chat some more about TypeScript, React, and frontend web development. Unsubscribe at any time.
Logo for Data Structures and Algorithms
Data Structures and Algorithms
Check out my courses!
If you enjoy my posts, you might enjoy my courses, too. Click the button to view the course or go to Courses for more information.