Skip to content

Instantly share code, notes, and snippets.

@marcuswestin
Last active December 17, 2015 11:49
Show Gist options
  • Save marcuswestin/5605389 to your computer and use it in GitHub Desktop.
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).
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