Created
February 21, 2016 08:43
-
-
Save tleb/713f13c4b61600eed628 to your computer and use it in GitHub Desktop.
type() function
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
/** | |
* @link http://stackoverflow.com/a/20441656/4255615 | |
*/ | |
var type = function(thing) { | |
var typeOfThing = typeof thing; | |
if (typeOfThing === 'object') { | |
typeOfThing = Object.prototype.toString.call(thing); | |
if (typeOfThing === '[object Object]') { | |
if (thing.constructor.name) { | |
return thing.constructor.name; | |
} else if (thing.constructor.toString().charAt(0) === '[') { | |
typeOfThing = typeOfThing.substring(8, typeOfThing.length - 1); | |
} else { | |
typeOfThing = thing.constructor.toString().match(/function\s*(\w+)/); | |
if (typeOfThing) { | |
return typeOfThing[1]; | |
} else { | |
return 'Function'; | |
} | |
} | |
} else { | |
typeOfThing = typeOfThing.substring(8, typeOfThing.length - 1); | |
} | |
} | |
return typeOfThing.charAt(0).toUpperCase() + typeOfThing.slice(1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment