Last active
March 21, 2022 01:26
-
-
Save ccurtin/43cbf472766c58b67a8a119a2ea756bb to your computer and use it in GitHub Desktop.
isNumber
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
// @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) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
TODO:
expect(isNumeric(0xFEFE)).toBe(false)
returnstrue
, and decide... should Hexidecimal andInfinity
be included?