Skip to content

Instantly share code, notes, and snippets.

@uolcano
Last active August 25, 2016 15:20
Show Gist options
  • Save uolcano/e4d7a288bc6f092794dd020d09694e83 to your computer and use it in GitHub Desktop.
Save uolcano/e4d7a288bc6f092794dd020d09694e83 to your computer and use it in GitHub Desktop.
get the accurate type of certain data by native JavaScript
var _create = Object.create,
_slice = Array.prototype.slice,
_toString = Object.prototype.toString,
_hasOwn = Object.prototype.hasOwnProperty;
/**
* [getTypeOf Get the data type of some data]
* @param {any type} arg [the data to get type]
* @return { string } [the string to describe the data type]
*
* usage:
* getTypeOf(1) === 'number'
* getTypeOf(null) === 'null'
* getTypeOf(NaN) === 'NaN'
* getTypeOf([1,2,3]) === 'array'
* getTypeOf(new Number(1)) === 'object number'
* getTypeOf(new Error('error')) === 'error'
* getTypeOf(new function Foo(){}) === 'foo'
* getTypeOf(window) === 'window'
* getTypeOf(document) === 'htmldocument'
* getTypeOf(document.createTextNode('hello')) === 'text'
*/
function getTypeOf(arg) {
var t1, t2;
if((t1 = typeof arg) === 'object') {
t2 = _toString.call(arg).slice(8, -1).toLowerCase();
switch(t2) {
case 'number':
case 'string':
case 'boolean':
// 'object number','object string','object boolean'
return [t1, t2].join(' ');
case 'null':
case 'array':
case 'date':
case 'regexp':
return t2;
default:
// 'person'
return arg.constructor.toString().match(/function\s*([^\(\s]*)/)[1].toLowerCase();
}
} else if (t1 === 'function') {
return t1;
} else {
switch (t1) {
case 'undefined':
case 'boolean':
case 'string':
return t1;
case 'number':
if(isNaN(arg)) return 'NaN';
if(!isFinite(arg)) return 'Infinity';
return t1;
default:
console.log('Error: type - something get wrong.');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment