Last active
April 2, 2021 04:54
-
-
Save rgchris/177e70ee3cf1696f13410a49df95783e to your computer and use it in GitHub Desktop.
A type-checking function in JavaScript
This file contains 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
window.istype = function(value, explicit = false) { | |
let type = Object.prototype.toString.apply(value).match( | |
/\[object ([A-Za-z_0-9]+)\]/ | |
)[1] | |
switch (type) { | |
case "Boolean": | |
case "String": | |
case "BigInt": | |
case "Undefined": | |
case "Null": | |
case "Symbol": | |
case "Array": | |
case "Date": | |
case "RegExp": | |
case "Function": | |
case "Error": | |
break | |
case "Number": | |
if (!Number.isFinite(value)) type = Number.isNaN(value) | |
? "NaN" | |
: "Infinity" | |
break | |
default: | |
if (!explicit) type = "Object" | |
} | |
return type | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment