Skip to content

Commit

Permalink
Faster string checking
Browse files Browse the repository at this point in the history
  • Loading branch information
benaadams committed Mar 30, 2018
1 parent 7ed4357 commit 8f544bf
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 11 deletions.
27 changes: 16 additions & 11 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,22 @@
'use strict';

module.exports = function isNumber(num) {
var type = typeof num;

if (type === 'string') {
// both a non-empty whitespace string and an empty string will be coerced to 0
// with the logic below. By stripping whitespace we can guarantee a correct result.
if (num.trim() === '') {
return false;
}
} else if (type !== 'number') {
var number = +num;

if ((number - number) !== 0) {
// Discard Infinity and NaN
return false;
}

return (num - num + 1) === 1;

if (number === num) {
return true;
} else if (typeof num === 'string') {
// String parsed, both a non-empty whitespace string and an empty string
// will have been coerced to 0. If 0 trim the string and see if its empty.
if (number === 0 && num.trim() === '') {
return false;
}
return true;
}
return false;
};
1 change: 1 addition & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,7 @@ describe('is not a number', function() {
function() {},
function() {},
Infinity,
-Infinity,
Math.sin,
NaN,
new Array(''),
Expand Down

0 comments on commit 8f544bf

Please sign in to comment.