I have created a clamp
function to bound value in a given range. (Almost every one of you know what a clamp function does)
So this the function I created (using TS
)
function clamp(value: number, min: number, max: number) {
return Math.min(Math.max(value, min), max)
}
but, there are some use cases where I want to get rid of converting all three params
to Number
type to pass it inside the function. I know I would have done something like this
function clamp(value: number, min: number, max: number) {
return Math.min(Math.max(Number(value), Number(min)), Number(max))
}
converting every single param
to Number
type.
I want to know if there is/are any other way/ways where I can just convert every
param
toNumber
type at once??
CodePudding user response:
You can use Array.map
to convert all values to Number
at once. In plain old JS:
function allNumbers(...values) {
return values.map(Number).filter(v => !isNaN(v));
}
console.log(`${allNumbers(1,`26`, 42)}`);
console.log(`${allNumbers(...[...`123`])}`);
console.log(`${allNumbers(`20`, ` `, `22`, `=`, 42)}`);
console.log(`${allNumbers(...(`20 22=42`.split(/[ =]/)))}`);
Typescript:
function clamp(...values: Array<number|string>) {
const numbers: (number|Nan)[] = values.map(Number);
if (numbers.filter(v => !isNaN(v)).length === 3) {
const [value, min, max] = numbers;
return Math.min(Math.max(value, min), max);
}
return `insufficient argument(s)`;
}
console.log(clamp(42));
console.log(clamp(1,3,`42`));
CodePudding user response:
Yes, instead of using the 'Number' constructor to convert each parameter individually, you can use the ' ' operator to convert all of the parameters to the 'Number' type in one step.
Here is an example of how you could use the ' ' operator to convert all of the parameters to the 'Number' type in your 'clamp' function:
function clamp(value: number, min: number, max: number) {
// Use the ' ' operator to convert all of the parameters to the 'Number' type
return Math.min(Math.max( value, min), max)
}
The ' ' operator is a shorthand way of converting a value to a number. When used with a numeric value, it simply returns the original value. However, when used with a non-numeric value (such as a string), it converts the value to a number.
In the example above, the ' ' operator is used to convert the 'value', 'min', and 'max' parameters to the 'Number' type before passing them to the 'Math.min' and 'Math.max' functions.
You can use this technique to avoid having to convert each parameter to the 'Number' type individually, making your code more concise and easier to read.