Last active
December 16, 2015 00:49
-
-
Save stamat/5350347 to your computer and use it in GitHub Desktop.
JavaScript data types
This file contains 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
//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