Last active
March 18, 2016 14:55
-
-
Save moimikey/372a12dcd9867e67c362 to your computer and use it in GitHub Desktop.
really simple javascript type detection
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
const assert = function (condition) { | |
if (condition !== true && condition !== false) { | |
throw new TypeError("Assertions should be only of booleans; you're writing your spec wrong."); | |
} | |
if (!condition) { | |
throw new Error("Specification-level assertion failure"); | |
} | |
}; | |
function whatIs(this$) { | |
switch(typeof this$) { | |
case 'string': | |
return 'string' | |
case 'object': | |
if (this$ === null) return 'null' | |
if (Array.isArray(this$)) return 'array' | |
return 'object' | |
case 'number': | |
if (Number.isNaN(this$)) return 'nan' | |
if (Number.isSafeInteger(this$)) return 'number' | |
if (Number.isFinite(this$)) return 'float' | |
return 'infinity' | |
case 'undefined': | |
return 'undefined' | |
case 'function': | |
return 'function' | |
case 'boolean': | |
return 'boolean' | |
case 'symbol': | |
return 'symbol' | |
default: | |
return 'unsure?' | |
} | |
} | |
assert(whatIs(Math.PI) === 'float') | |
assert(whatIs(666) === 'number') | |
assert(whatIs(+0) === 'number') | |
assert(whatIs(-0) === 'number') | |
assert(whatIs('hello world') === 'string') | |
assert(whatIs(undefined) === 'undefined') | |
assert(whatIs(Infinity) === 'infinity') | |
assert(whatIs(-Infinity) === 'infinity') | |
assert(whatIs(+Infinity) === 'infinity') | |
assert(whatIs({}) === 'object') | |
assert(whatIs([]) === 'array') | |
assert(whatIs(function(){}) === 'function') | |
assert(whatIs(null) === 'null') | |
assert(whatIs(true) === 'boolean') | |
assert(whatIs(Symbol()) === 'symbol') | |
// assert(whatIs({"a":"a"}) === 'json') // soon... soon... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment