I recently created a clamp
function to restrict values within a specified range. (I'm sure most of you are familiar with what a clamp function does)
Here is the function I came up with (using TS
)
function clamp(value: number, min: number, max: number) {
return Math.min(Math.max(value, min), max)
}
However, there are certain scenarios where I don't want to manually convert all three params
to type Number
before passing them into the function. One approach I thought of was like this:
function clamp(value: number, min: number, max: number) {
return Math.min(Math.max(Number(value), Number(min)), Number(max))
}
This involves converting each individual param
to type Number
.
Is there an alternative method to convert all params
to type Number
in one go?
I am still on the lookout for simpler solutions! ðŸ«