Skip to content

Instantly share code, notes, and snippets.

@stamat
Last active December 16, 2015 00:49
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 stamat/5350347 to your computer and use it in GitHub Desktop.
Save stamat/5350347 to your computer and use it in GitHub Desktop.
JavaScript data types
//Thanks to perfectionkills.com <http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/>
__getClass = function(val) {
return Object.prototype.toString.call(val)
.match(/^\[object\s(.*)\]$/)[1];
};
var whatis = function(val) {
if(val === undefined)
return 'undefined';
if(val === null)
return 'null';
var type = typeof val;
if(type === 'object') {
type = __getClass(val).toLowerCase();
}
if(type === 'number') {
if(val.toString().indexOf('.') > 0)
return 'float';
else
return 'integer';
}
return type;
};
var isSet = function(val) {
return (val !== undefined) && (val !== null);
};
var isEmpty = function(obj) {
if (obj.length && obj.length > 0)
return false;
for (var key in obj) {
if (hasOwnProperty.call(obj, key))
return false;
}
return true;
};
var is = function(obj, type) {
if (type === 'number')
return isNumber(obj);
if (whatis(obj) === type)
return true;
if (type === 'empty')
return isEmpty(obj);
if (type === 'set')
return isSet(obj);
return false;
};
var isArray = function(val) {
return is(val, 'array');
};
var isNumber = function(val) {
if (isNaN(val))
return false;
var type = typeof val;
if (type === 'object')
type = __getClass(val).toLowerCase();
return type === 'number';
};
var isInt = function(val) {
return is(val, 'integer');
};
var isFloat = function(val) {
return is(val, 'float');
};
var isString = function(val) {
return is(val,'string');
};
var isObject = function(val) {
return is(val, 'object');
};
var isFunction = function(val) {
return is(val, 'function');
};
var isDate = function(val) {
return is(val,'date');
};
var isBool = function(val) {
return is(val, 'boolean');
};
var isRegExp = function(val) {
return is(val, 'regexp');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment