Skip to content

Instantly share code, notes, and snippets.

@tleb
Created February 21, 2016 08:43
Show Gist options
  • Save tleb/713f13c4b61600eed628 to your computer and use it in GitHub Desktop.
Save tleb/713f13c4b61600eed628 to your computer and use it in GitHub Desktop.
type() function
/**
* @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