Last active
December 17, 2015 11:49
-
-
Save marcuswestin/5605389 to your computer and use it in GitHub Desktop.
Exploration of object type detection by equality testing of member methods (notably toString).
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
function isArray(obj) { | |
return obj && obj.toString == Array.prototype.toString | |
} | |
function isNumber(obj) { | |
return obj && obj.toString == Number.prototype.toString | |
} | |
function isString(obj) { | |
return obj && obj.toString == String.prototype.toString | |
} | |
function isArguments(obj) { | |
return obj && Object.prototype.toString.call(obj) == '[object Arguments]' | |
} | |
function isObject(obj) { | |
return obj && obj.toString == Object.prototype.toString && !isArguments(obj) | |
} | |
var identifyingFunctions = [isObject, isArray, isNumber, isString] | |
test({}, isObject) | |
test([], isArray) | |
test(1, isNumber) | |
test('a', isString) | |
var arguments = (function() { return arguments }()) | |
test(arguments, isArguments) | |
function test(obj, correctIdentifyingFunction) { | |
for (var i=0, identifyingFunction; identifyingFunction = identifyingFunctions[i]; i++) { | |
if (identifyingFunction == correctIdentifyingFunction) { | |
assert(identifyingFunction(obj)) | |
} else { | |
assert(!identifyingFunction(obj)) | |
} | |
} | |
} | |
function assert(truthy) { | |
if (!truthy) { throw new Error("Assertion failed") } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment