Last active
January 16, 2024 01:16
-
-
Save jonbretman/7259628 to your computer and use it in GitHub Desktop.
Simple type checking 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
(function (root) { | |
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; | |
}; | |
var types = [ | |
'Null', | |
'Undefined', | |
'Object', | |
'Array', | |
'String', | |
'Number', | |
'Boolean', | |
'Function', | |
'RegExp', | |
'Element', | |
'NaN', | |
'Infinite' | |
]; | |
var generateMethod = function (t) { | |
type['is' + t] = function (o) { | |
return type(o) === t.toLowerCase(); | |
}; | |
}; | |
for (var i = 0; i < types.length; i++) { | |
generateMethod(types[i]); | |
} | |
if (typeof exports === "object" && exports) { | |
exports = type; | |
} | |
else if (typeof define === "function" && define.amd) { | |
define(type); | |
} | |
else { | |
root.type = type; | |
} | |
})(this); |
Jon, I listend to you awesome talk at JSConf.eu 2013 and have been using the type() method you proposed in your presentation in some of my hobby projects since then (most usually to assert parameter values).
I'd love to see this as an npm plugin, that i don't need to copy it in every project! ;)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Checkout http://jsperf.com/type-cecking for some performance comparisons…