Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
A couple of useful utility functions for working with JS types.
;(function() {
var global = this;
// Get the default value for a named type (primitive name, 'function' or name of constructor).
function defaultValue(type) {
if (typeof type !== 'string') throw new TypeError('Type must be a string.');
// Handle simple types (primitives and plain function/object)
switch (type) {
case 'boolean' : return false;
case 'function' : return function () {};
case 'null' : return null;
case 'number' : return 0;
case 'object' : return {};
case 'string' : return "";
case 'symbol' : return Symbol();
case 'undefined' : return void 0;
}
try {
// Look for constructor in this or current scope
var ctor = typeof this[type] === 'function'
? this[type]
: eval(type);
return new ctor;
// Constructor not found, return new object
} catch (e) { return {}; }
}
// Get the type name of an object (primitive name, 'function' or name of constructor).
function getType(obj) {
var type = typeof obj;
if (type !== 'object') return type; // primitive or function
if (obj === null) return 'null'; // null
// Everything else, check for a constructor
var ctor = obj.constructor;
var name = typeof ctor === 'function' && ctor.name;
return typeof name === 'string' && name.length > 0 ? name : 'object';
}
var TypeUtil = {
defaultValue : defaultValue,
getType : getType
};
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = TypeUtil;
} else {
global.TypeUtil = TypeUtil;
}
}).call(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment