That's one line of code in your utils module...
That's one line of code in your utils module...
For isEven, you first need isNumber. And that’s where the complexity lies.
({}) % 2 == 0 // false
([]) % 2 == 0 // true
"" % 2 == 0 // true
"a" % 2 == 0 // false
"1" % 2 == 0 // false
"2" % 2 == 0 // true
undefined % 2 == 0 // false
null % 2 == 0 // trueI am literally not joking. https://www.npmjs.com/package/is-even
I don't know what to say.
/**
* is-odd-and-even
* Github: https://github.com/fabrisdev/is-odd-and-even
*/
import isOdd from 'is-odd'
import isEven from 'is-even'
/**
* @param {number | string} i The number to check if it's odd and even
* @returns {boolean} True if the number is odd and even, false otherwise
*/
export default function isOddAndEven(i){
return isOdd(i) && isEven(i)
}Your isEven function should check that it's operating on a number. Eg "const isEven = (i) => typeof i === 'number' && i % 2===0;" If it's not a number then calling isEven on it doesn't make sense. If the user wants to check if a string is even then they can convert it before making the call.
A proper solution would be along the lines of:
const isRealNumber = (n) => {
if (typeof n !== 'number') return false;
if (isNaN(n)) return false;
if (n === +Inf || n === -Inf) return false;
return true;
};
const isEven = (n) => {
if (!isNumber(n)) throw new Error("Numerical error: Invalid input");
return n % 2 === 0;
}
const isOdd = (n) => {
if (!isNumber(n)) throw new Error("Numerical error: Invalid input");
return n % 2 !== 0;
}
This is the additional complexity created by dynamically weakly typed languages. And that’s why we get all these BS tiny npm packages.'isEven' really shouldn't be a dependency though, either through npm or internally. 'x % 2 === 0' works fine for integers and can be inlined, or if you're using it a bunch and want slightly cleaner code, you can define it as a lambda alongside the code that uses it. Then everyone can see exactly what it's doing with the full context.
The real issue is overabstraction. Even if you do everything "right" and have it as an internal dependency with all the correct error handling, it still makes the code a pain in the ass to read.
If the goal of isEven is to handle user input, it is woefully misnamed.