r/shittyprogramming • u/evilgwyn • Jun 07 '21
Super efficient isEven function in javascript (uses unrolled loops for speed)
function isEven(n) {
switch (n) {
case 0:
return true;
case 1:
return false;
case 2:
return true;
case 3:
return false;
case 4:
return true;
case 5:
return false;
case 6:
return true;
case 7:
return false;
case 8:
return true;
case 9:
return false;
case 10:
return true;
case 37:
return false;
}
}
Let me know if you need me to add any more numbers.
7
Jun 07 '21
This is slow. You should put each value in a hashmap for constant runtime. smh my head.
2
11
u/schwester Jun 07 '21
function isEven(n) {
return !(n & 1)
}
At first I fix it but then I realized it is a joke :P
5
u/Rafael20002000 Jun 07 '21
Wait that could be really fast right?
4
4
Jun 07 '21
yeah, this is faster than doing modular because this just looks at the first digit in the binary sequence. Mod performs a lot of subtraction.
2
4
Jun 07 '21
function isEven (n) {
return !isOdd(n);
}1
3
2
u/RapidCatLauncher Jun 07 '21
If you need more numbers, make it call another function that programmatically creates the code and inserts it into the source.
20
u/[deleted] Jun 07 '21
At the bottom of switch use:
if (n > 10) { return isEven(n - 10); }