Skip to content

Instantly share code, notes, and snippets.

@simonrenoult
Last active December 29, 2015 07:49
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 simonrenoult/7639373 to your computer and use it in GitHub Desktop.
Save simonrenoult/7639373 to your computer and use it in GitHub Desktop.
Checking types.
// Props to : http://techblog.badoo.com/blog/2013/11/01/type-checking-in-javascript/
var type = function (o) {
// handle null in old IE
if (o === null) {
return 'null';
}
// handle DOM elements
if (o && (o.nodeType === 1 || o.nodeType === 9)) {
return 'element';
}
var s = Object.prototype.toString.call(o);
var type = s.match(/\[object (.*?)\]/)[1].toLowerCase();
// handle NaN and Infinity
if (type === 'number') {
if (isNaN(o)) {
return 'nan';
}
if (!isFinite(o)) {
return 'infinity';
}
}
return type;
};
['Null',
'Undefined',
'Object',
'Array',
'String',
'Number',
'Boolean',
'Function',
'RegExp',
'Element',
'NaN',
'Infinite'
].forEach(function (t) {
type['is' + t] = function (o) {
return type(o) === t.toLowerCase();
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment