Hacker News new | ask | show | jobs
by robert-boehnke 2200 days ago
Note that this implementation of `isEven` throws on input that isn't a number or numbers that are not integers, NaN or larger than 2^53-1. I think it's fair to argue an implementation could just as well return false for 1.4, NaN or '2'. There is a cost to learning these minutiae of your dependencies, especially if there is no compiler support to assist you.
1 comments

I've not programmed a lot of JS, so this might be obvious for someone who did, but:

Why does he first use Math.abs on the parameter and then type check the result of that? I'd think if you do an argument type check, you'd do it before using it. Just to make it not throw on null? I don't see the sense in that...

I'm not sure this is the reason for that specific implementation but `Math.abs` _will_ do a string-to-number conversion.

I.e., `Math.abs("-27")` yields `27`.

It might be the case that Math.abs does other *-to-number conversions also, so maybe this method is trying to take advantage of that. (Math.abs is usually implemented as a native function so without digging more deeply it's not obvious to me what the actual implementation does.)

UPDATE: Curiously, `Math.abs(null)` yields `0`, so a null argument passed to is-even would yield `true` I guess.

Also whatever the logic is for that conversion is it is not the same as the built-in `parseInt` or `parseFloat`. `parseInt("27 meters")` yields `27` but `Math.abs("27 meters")` yields `NaN`.

Personally in JavaScript I almost universally make use of home-grown `isInt` and `toInt` methods whose behavior is predicable for me -- eg. my toInt() will reject a string that's not _just_ an integer value (and return `null` rather than `NaN` in all cases because who wants to check `isNaN`?) -- but that's probably not a great practice either. But I've been programming long enough to realize that the principle of least surprise is probably the most important concern here for long-term efficiency. I suppose what is or is not surprising may be subjective though.