jonschlinkert / is-number

JavaScript/Node.js utility. Returns `true` if the value is a number or string number. Useful for checking regex match results, user input, parsed strings, etc.
https://github.com/jonschlinkert
MIT License
260 stars 50 forks source link

Optimizing even further #36

Open theUpsider opened 2 years ago

theUpsider commented 2 years ago

image Extremely faster speeds on "all" tests. Also not significantly worse in individual tests.

EdwardDrapkin commented 8 months ago

This one's faster:

image


function isNumber64(num) {
  switch (true) {
  case num == null:
    return false;
  case typeof num === 'number':
    return num - num === 0;
  case typeof num === 'string' && num.trim().length > 0:
    return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);
  default:
    return false;
  }
}

Even better:

image

function isNumber65(num) {
  switch (true) {
  case typeof num === 'number':
    return num - num === 0;
  case typeof num === 'string':
    for (let i = 0; i < num.length; i++) {
      if (num.charCodeAt(i) !== 32 && num.charCodeAt(i) !== 13 && num.charCodeAt(i) !== 10 && num.charCodeAt(i) !== 9) {
        return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);
      }
    }

    return false;

  default:
    return false;
  }
}