Created
October 7, 2009 23:54
-
-
Save steida/204554 to your computer and use it in GitHub Desktop.
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
/* | |
* Sugar for type detection working across frames and browsers ;) | |
* | |
* Detected types | |
* | |
* 'arguments', 'array', 'boolean', 'date', 'document', 'element', 'error', 'fragment', | |
* 'function', 'nodelist', 'null', 'number', 'object', 'regexp', 'string', 'textnode', | |
* 'undefined', 'window' | |
* | |
* Copyright (c) 2009 Daniel Steigerwald (http://daniel.steigerwald.cz), Mit Style License | |
*/ | |
var $type = (function() { | |
var toString = Object.prototype.toString, | |
toStrings = {}, | |
nodeTypes = { 1: 'element', 3: 'textnode', 9: 'document', 11: 'fragment' }, | |
types = 'Arguments Array Boolean Date Document Element Error Fragment Function NodeList Null Number Object RegExp String TextNode Undefined Window'.split(' '); | |
for (var i = types.length; i--; ) { | |
var type = types[i], constructor = window[type]; | |
if (constructor) { | |
try { toStrings[toString.call(new constructor)] = type.toLowerCase(); } | |
catch (e) { } | |
} | |
} | |
return function(item) { | |
return item == null && (item === undefined ? 'undefined' : 'null') || | |
item.nodeType && nodeTypes[item.nodeType] || | |
typeof item.length == 'number' && ( | |
item.callee && 'arguments' || | |
item.alert && 'window' || | |
item.item && 'nodelist') || | |
toStrings[toString.call(item)]; | |
}; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for quick review. The code is very very old, from times when NodeJS didn't exists. I do not use it anymore, because https://github.com/Steida/este. Google Closure has own type detection, handling edge cases better http://code.google.com/p/closure-library/source/browse/trunk/closure/goog/base.js?r=2#536.
Ad syntax: How I would write it today :-)