Skip to content

Instantly share code, notes, and snippets.

@LeanSeverino1022
Last active January 11, 2020 16:41
Show Gist options
  • Save LeanSeverino1022/574270fb13e1b225ebee6f16971d6f57 to your computer and use it in GitHub Desktop.
Save LeanSeverino1022/574270fb13e1b225ebee6f16971d6f57 to your computer and use it in GitHub Desktop.
type checking techniques #types #vanillajs
//src: https://vanillajstoolkit.com/helpers/truetypeof/
/*!
* More accurately check the type of a JavaScript object
* (c) 2018 Chris Ferdinandi, MIT License, https://gomakethings.com
* @param {Object} obj The object
* @return {String} The object type
*/
var trueTypeOf = function (obj) {
return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
};
console.log( trueTypeOf([]) ); //"array"
var elemCheck = {};
elemCheck.isArray = function(elem) {
return Object.prototype.toString.call(elem).slice(8,-1) === 'Array';
}
elemCheck.isObject = function(elem) {
return Object.prototype.toString.call(elem).slice(8,-1) === 'Object';
}
elemCheck.isString = function(elem) {
return Object.prototype.toString.call(elem).slice(8,-1) === 'String';
}
elemCheck.isDate = function(elem) {
return Object.prototype.toString.call(elem).slice(8,-1) === 'Date';
}
elemCheck.isRegExp = function(elem) {
return Object.prototype.toString.call(elem).slice(8,-1) === 'RegExp';
}
elemCheck.isFunction = function(elem) {
return Object.prototype.toString.call(elem).slice(8,-1) === 'Function';
}
elemCheck.isBoolean = function(elem) {
return Object.prototype.toString.call(elem).slice(8,-1) === 'Boolean';
}
elemCheck.isNumber = function(elem) {
return Object.prototype.toString.call(elem).slice(8,-1) === 'Number';
}
elemCheck.isNull = function(elem) {
return Object.prototype.toString.call(elem).slice(8,-1) === 'Null';
}
elemCheck.isUndefined = function(elem) {
return Object.prototype.toString.call(elem).slice(8,-1) === 'Undefined';
}
console.log( elemCheck.isArray([]) );
console.log( elemCheck.isObject({}) ); // true
console.log( elemCheck.isString('') ); // true
console.log( elemCheck.isDate(new Date()) ); // true
console.log( elemCheck.isRegExp(/test/i) ); // true
console.log( elemCheck.isFunction(function () {}) ); // true
console.log( elemCheck.isBoolean(true) ); // true
console.log( elemCheck.isNumber(1) ); // true
console.log( elemCheck.isNull(null) ); // true
console.log( elemCheck.isUndefined() ); // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment