Skip to content

Instantly share code, notes, and snippets.

@moimikey moimikey/whatis.js
Last active Mar 18, 2016

Embed
What would you like to do?
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
You can’t perform that action at this time.