Skip to content

Instantly share code, notes, and snippets.

@moimikey
Last active March 18, 2016 14:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moimikey/372a12dcd9867e67c362 to your computer and use it in GitHub Desktop.
Save moimikey/372a12dcd9867e67c362 to your computer and use it in GitHub Desktop.
really simple javascript type detection
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