2 ms·
How do you handle someone inputting undefined/null/a string/a random object/NaN/etc? Your isEven function should check that it's operating on a number. Eg "con
by onion2k 5y ago
How do you handle someone inputting undefined/null/a string/a random object/NaN/etc?
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.
- jasonlotito 5y agoThe irony of using the isEven as an example of what you should just write yourself and then providing an example that returns a truthy value for isEven(3).
- onion2k 5y agoNo idea what you mean. ;)
- kuschku 5y agoNow someone is going to define const isOdd = (i) => !isEven(i); and you’ll get trouble. 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.