Created
April 8, 2015 18:48
-
-
Save alexcjohnson/a3b74c73a9d4ef872895 to your computer and use it in GitHub Desktop.
Test of various javascript isNumeric implementations
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
var shouldPass = [ | |
0xff, | |
5e3, | |
0, | |
-1.1, | |
37, | |
3.14, | |
1, | |
1.1, | |
10, | |
10.10, | |
100, | |
-100, | |
'-1.1', | |
'0', | |
'012', | |
'0xff', | |
'1', | |
'1.1', | |
'10', | |
'10.10', | |
'100', | |
'5e3', | |
Math.LN2, | |
Number(1), | |
new Number(1), | |
// 012, Octal literal not allowed in strict mode | |
parseInt('012'), | |
parseFloat('012'), | |
Math.abs(1), | |
Math.acos(1), | |
Math.asin(1), | |
Math.atan(1), | |
Math.atan2(1, 2), | |
Math.ceil(1), | |
Math.cos(1), | |
Math.E, | |
Math.exp(1), | |
Math.floor(1), | |
Math.LN10, | |
Math.LN2, | |
Math.log(1), | |
Math.LOG10E, | |
Math.LOG2E, | |
Math.max(1, 2), | |
Math.min(1, 2), | |
Math.PI, | |
Math.pow(1, 2), | |
Math.pow(5, 5), | |
Math.random(1), | |
Math.round(1), | |
Math.sin(1), | |
Math.sqrt(1), | |
Math.SQRT1_2, | |
Math.SQRT2, | |
Math.tan(1), | |
Number.MAX_VALUE, | |
Number.MIN_VALUE, | |
"0.0", | |
"0x0", | |
"0e+5", | |
"000", | |
"0.0e-5", | |
"0.0E5" | |
]; | |
var shouldFail = [ | |
'3abc', | |
'abc', | |
'abc3', | |
'null', | |
'undefined', | |
[1, 2, 3], | |
[1], | |
[], | |
function () {}, | |
Infinity, | |
NaN, | |
new Array('abc'), | |
new Array(0), | |
new Array(2), | |
null, | |
undefined, | |
{abc: 'abc'}, | |
{}, | |
'' | |
]; | |
function testNumFunction(f) { | |
var failures = shouldPass.filter(function(n) { return !f(n); }) | |
.concat(shouldFail.filter(f)); | |
if(failures.length) { | |
console.log(failures); | |
return false; | |
} | |
return true; | |
} | |
//jQuery 1.x | |
function isNumericJQ1(n) { | |
return !isNaN(parseFloat(n)) && isFinite(n); | |
} | |
//jQuery 2.x | |
function isNumericJQ2(obj) { | |
return !Array.isArray( obj ) && (obj - parseFloat( obj ) + 1) >= 0; | |
} | |
//npm isNumber | |
function isNumber(n) { | |
return (!!(+n) && !Array.isArray(n)) && isFinite(n) | |
|| n === '0' | |
|| n === 0; | |
} | |
//modified npm isNumber | |
function isNumber2(n) { | |
return !!(+('1'+n) || +(n+'1')) && !Array.isArray(n) && isFinite(n) && (n !== ''); | |
} | |
testNumFunction(isNumericJQ1); // fails on [1] | |
testNumFunction(isNumericJQ2); // passes | |
testNumFunction(isNumber); // fails on ["0.0", "0x0", "0e+5", "000", "0.0e-5", "0.0E5"] | |
testNumFunction(isNumber2); // passes |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment