Skip to content

Instantly share code, notes, and snippets.

@jordangray
Created February 25, 2015 00:32
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 jordangray/f0ece13c3959d0387a81 to your computer and use it in GitHub Desktop.
Save jordangray/f0ece13c3959d0387a81 to your computer and use it in GitHub Desktop.
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