I work with Javascript (Typescript), more specifically with React. So this question is written in Javascript but it's more like a general question.
I'm trying to refactor some code and extract static methods. Once I extract the method, I find myself checking if all arguments received are valid. This becomes hard to read and, sometimes, the real purpose of the function has only a few lines.
Here's an example of how I would end up writing a method / function
const isGreaterThan = (value1, value2) => {
if(typeof value1 !== 'number'){
console.error("Invalid argument. value1 must be a number");
return 0;
}
if(typeof value2 !== 'number'){
console.error("Invalid argument. value2 must be a number");
return 0;
}
return value1 > value2
}
Now imagine if this method receives an Array
const isGreaterThanAll = (values, value1) => {
if(!values instanceof Array){
console.error("Invalid argument. values must be an Array");
return 0;
}
if(!values.every(value => typeof value === 'number')){
console.error("Invalid argument. elements of values must be numbers");
return 0;
}
if(typeof value1 !== 'number'){
console.error("Invalid argument. value2 should be type of number");
return 0;
}
return values.every(value => value1 > value);
}
Now imagine passing an Object or an Array of Objects. Depending on the complexity of the arguments, this becomes harder to follow.
Some of my questions are:
One way to do it is to create a recursive function like this.
const isNumberOrArrayOfNumbers = (x) => {
if (typeof x === 'number') {
return true;
}
if ( Array.isArray(x) ) {
return x.every(n => isNumberOrArrayOfNumbers(n));
}
return false;
};
const isGreaterThanAll = (values, value1) => {
let valid = [values, value1].every(a => isNumberOrArrayOfNumbers(a));
if (!valid) {
console.error('Invalid');
return Number.NaN;
}
return values.every(value => value1 > value);
};
console.log( isGreaterThanAll([1,2,3,5,6,7],12) );
console.log( isGreaterThanAll([1,2,3,5,6,7],4) );
console.log( isGreaterThanAll([1,2,3,"r",5,6,7],12) );
If you're willing to change the signature of the function you could also refactor by making it variadic and using rest operators
That might look something like this:
const isGreaterThanAll = (n, ...m) => {
let valid = [n, ...m].every(x => typeof x === 'number');
...
};