I've got a number, and I want that number, or 0 or 100 if it overflows in either direction
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)
— John Norris
Who are Dragon Drop?
Dragon Drop is a specialist web and app development agency. The team has extensive full-stack technical credentials and a strong focus on user experience.
The Dragon Drop founding team have over 40 years of web development and project experience. They have managed or developed over 100 significant ecommerce and web projects during their careers, including implementations for major UK high street retailers, financial services companies and government agencies.
Their approach to innovative solutions stems from perspectives gained as retailer, software supplier and web agency.