Created
July 1, 2013 23:01
-
-
Save nickjacob/5905401 to your computer and use it in GitHub Desktop.
rly simple self-defining test function snippet
This file contains hidden or 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
/* Just define a simple is_a fn and populate it with functions | |
* that correspond to the primary JS objects; interface is | |
* | |
* is_a.array([]) >> true | |
*/ | |
;(function (window, undefined){ | |
var upFirst = /^(\w)/, | |
toS = Object.prototype.toString, | |
builtIns = ['Array', 'Object', 'Number', 'String', 'Window', 'RegExp', 'Function']; | |
function up(str) { | |
return str.replace(upFirst, function($0, $1){ return $1.toUpperCase();}); | |
} | |
function makeTest(_type) { | |
_type = up(_type); | |
return function (o) { | |
toS.call(o) === "[object " + _type + "]"; | |
} | |
} | |
function is_a(_type, obj) { | |
return (is_a[_type] = (is_a[_type] !== undefined ? is_a[_type] : makeTest(_type)))(obj); | |
} | |
// set up all the built ins, attach is_a to the window | |
var i = 0, len = builtIns.length; | |
for(; i < len; i++) { | |
is_a(builtIns[i]); | |
} | |
window.is_a = is_a; | |
}(window)); | |
// usage | |
is_a('function', fn); | |
is_a.Function(fn); | |
is_a.Number(num); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment