Javascript - Efficient even-odd checking

/** * Returns: * - 1 if n is odd * - 0 if n is even */ function isOdd(n) { return n & 1; } // Variants for boolean result function isOdd(n) { return (n & 1) === 1; } function isEven(n) { return (n & 1) === 0; } // Other variants for boolean result function isOdd(n) { return !!(n & 1); } function isEven(n) { return !(n & 1); } // Functional approach function checkParity(odd) { return function(n) { return (n & 1) == odd; }; } // ... more intuitive function checkParity(even) { return function(n) { return !(n & 1) === even; }; } var isOdd = checkParity(false); // checkParity(1); var isEven = checkParity(true); // checkParity(0); console.log(3, 'odd ', isOdd(3)); // true console.log(4, 'odd ', isOdd(4)); // false console.log(3, 'even', isEven(3)); // false console.log(4, 'even', isEven(4)); // true
This is a more efficient approach for even-odd checking then the classic "modulo" one.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.