Created
July 7, 2014 00:53
-
-
Save jdfm/49b3e689ca65929c56b3 to your computer and use it in GitHub Desktop.
Determine if a number is an integer or not.
This file contains 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
var isInteger = (function(NEGATIVE_INFINITY, POSITIVE_INFINITY){ | |
return function(n){ | |
return typeof n === 'number' && // Are you even an number? Rules out non numeric types. | |
n > NEGATIVE_INFINITY && // n larger than negative infinity? Rules out NaN and negative infinity. | |
n < POSITIVE_INFINITY && // n smaller than positive infinity? Rules out NaN and positive infinity. | |
!(n % 1); // n has a remainder of 0 when calculating modulo 1? Rules out floating points. | |
}; | |
}(-1/0, 1/0)); // just making sure we're getting negative and positive infinity | |
console.assert(isInteger(false) === false, 'booleans are not integers') | |
console.assert(isInteger(function(){}) === false, 'functions are not integers') | |
console.assert(isInteger(/1/) === false, 'regexps are not integers') | |
console.assert(isInteger([1]) === false, 'arrays are not integers') | |
console.assert(isInteger(Object(1)) === false, 'objects are not integers') | |
console.assert(isInteger('1') === false, 'strings are not integers') | |
console.assert(isInteger(Number.POSITIVE_INFINITY) === false, 'Infinity is not an integer') | |
console.assert(isInteger(Number.NEGATIVE_INFINITY) === false, '-Infinity is not an integer') | |
console.assert(isInteger(NaN) === false, 'NaN is not an integer') | |
console.assert(isInteger(1.1) === false, 'Floating points are not integers') | |
console.assert(isInteger(1) === true, '1 is an integer') | |
console.assert(isInteger(0) === true, '0 is an integer') | |
console.assert(isInteger(-0) === true, '-0 is an integer') | |
console.assert(isInteger(-1) === true, '-1 is an integer') | |
console.log('Everything is in working order.'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment