Skip to content

Instantly share code, notes, and snippets.

@ccurtin
Last active March 21, 2022 01:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ccurtin/43cbf472766c58b67a8a119a2ea756bb to your computer and use it in GitHub Desktop.
Save ccurtin/43cbf472766c58b67a8a119a2ea756bb to your computer and use it in GitHub Desktop.
isNumber
// @see: https://jsben.ch/cQk7m
// NOTE: `+val === +val` is like isNaN(val) but much faster, esp in Chrome...
// `+val` will convert a string containing a number into a number
// const isNumeric = (val) => (val && val.length || typeof val === 'number') && (+val === +val);
const isNumeric = (val) => ((val?.length || typeof val === 'number') && (+val === +val)) && !isNaN(parseFloat(val))
isNumeric(12345678912345678912);
isNumeric('2');
isNumeric('-32.2');
isNumeric(+"32df32sddfadf22");
isNumeric(undefined);
isNumeric('');
isNumeric(0);
isNumeric();
isNumeric(null);
isNumeric([]);
isNumeric('1e2');
isNumeric('1e2fd');
isNumeric(new Date());
isNumeric(Date.now());
isNumeric(Infinity);
isNumeric(-Infinity);
// // should be true
// expect(isNumeric(0)).toBe(true)
// expect(isNumeric(1)).toBe(true)
// expect(isNumeric(1234567890)).toBe(true)
// expect(isNumeric("1234567890")).toBe(true)
// expect(isNumeric("0")).toBe(true)
// expect(isNumeric("1")).toBe(true)
// expect(isNumeric("1.1")).toBe(true)
// expect(isNumeric("-1")).toBe(true)
// expect(isNumeric("-1.2354")).toBe(true)
// expect(isNumeric("-1234567890")).toBe(true)
// expect(isNumeric(-1)).toBe(true)
// expect(isNumeric(-32.1)).toBe(true)
// expect(isNumeric("0x1")).toBe(true)
// // should be false
// expect(isNumeric(true)).toBe(false)
// expect(isNumeric(false)).toBe(false)
// expect(isNumeric("1..1")).toBe(false)
// expect(isNumeric("1,1")).toBe(false)
// expect(isNumeric("-32.1.12")).toBe(false)
// expect(isNumeric("")).toBe(false)
// expect(isNumeric(" ")).toBe(false)
// expect(isNumeric(null)).toBe(false)
// expect(isNumeric(undefined)).toBe(false)
// expect(isNumeric([])).toBe(false)
// expect(isNumeric(NaN)).toBe(false)
@ccurtin
Copy link
Author

ccurtin commented Jan 12, 2022

TODO:

  • Fix... expect(isNumeric(0xFEFE)).toBe(false) returns true, and decide... should Hexidecimal and Infinity be included?
  • Add verbose test results and simple "expect" method to gist.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment