Created
April 27, 2012 12:18
-
-
Save janjongboom/2508732 to your computer and use it in GitHub Desktop.
isEven function for javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// efficient isEven function | |
// you can insert a number or a string, doesn't matter | |
// it doesn't take numbers after the dot into account because noone uses them anyways | |
// it's also very handy for shopping websites because you can do | |
// isEven("$ 31.00") and it will say 'not even'. | |
// or isEven("32.00 $") and will say 'even' | |
function isEven(a) { | |
a = a.toString().replace(/[^0-9.]/g, ""); | |
var stack = []; | |
var rev = a.split('').reverse(); | |
for (var ix = 0; ix < rev.length; ix++) { | |
if (rev[ix] == ".") stack.push("dot") | |
else if (rev[ix] == "1" || rev[ix] == "3" || rev[ix] =="5" || rev[ix] == "7" || rev[ix] == "9") | |
stack.push("odd") | |
else | |
stack.push('even') | |
} | |
var wholenumber = stack.splice(stack.indexOf("dot") + 1) | |
return wholenumber[0] == "even"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment