I've got a number, and I want that number, or 0 or 100 if it overflows in either direction

by John Norris

Conceptually, there has to be a better way of ensuring we get back a number between 0 and 100 than this?

Math.min(100, Math.max(0, number))

In Ruby we could do something like:

number.clamp(0, 100)

We can recreate this in Javascript with something like:

Number.prototype.clamp = function(min, max) {
  return Math.min(max, Math.max(min, this));
};

// which can be used like:

number.clamp(0, 100)

But, we should never prototype things like in that example, as is well documented.

So we should instead use a function:

const clamp = (min, max, num) => Math.min(max, Math.max(min, num))

Side fun; with the number at the end, we can use it as a curried function:

const clamp = (min, max) => num => Math.min(max, Math.max(min, num))

// which can be used like:

const clampPercentage = clamp(0, 100)
const clampedNumber = clampPecentage(num)