r/badcode • • Mar 26 '21

js Whose ever heard of %?

Post image
727 Upvotes

63 comments sorted by

View all comments

4

u/buffer_overfloooooow Mar 26 '21

Also dumb because it doesn't work for even one digit numbers

7

u/Vercyx Mar 26 '21

to be fair, it actually does since its < and not <=

so 4/2 is going to have a length of 1, which is not less than a length of 1

it technically works for all numbers but it's quite stupid otherwise

6

u/Andersmith Mar 27 '21

Technically it won’t work if given a non integer value (like .2), but input sanitation seems a bit too nitpicky of an issue for this sub.

3

u/Vercyx Mar 27 '21

I guess it depends if you consider .2 even or odd.

.2/2 = .1 which is a string of the same length, therefore it should be even

.3/2 = .15 which is longer, therefore should be odd

JS has implicit type casting so it doesn't really matter what the input is, it will return SOMETHING

7

u/ghillerd Mar 27 '21

parity is a property of integers, so an `isEven` function should return false for a non-integer, as should `isOdd`.

3

u/bphase Mar 27 '21

One could also argue for an exception, as you're violating the precondition of the number being an integer if you call it with a float.

1

u/ghillerd Mar 27 '21

True. If the function is supposed to be something like, getParity, and returns 0 or 1 depending on if it's even or odd, then it should definitely throw if you give it something other than an integer. With isEvenNumber, it's closer, because a string or a function or a decimal or whatever isn't an even number.