Skip to content

Instantly share code, notes, and snippets.

@stephband
Last active August 29, 2015 14:27
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 stephband/e30cbb43cff122403d05 to your computer and use it in GitHub Desktop.
Save stephband/e30cbb43cff122403d05 to your computer and use it in GitHub Desktop.
Overload a function according to the types of arguments passed in
// Overload a function according to the types of arguments passed in:
//
// var fn = overloadByTypes({
// 'object': function(object) {},
// 'string number': function(string, number) {},
// 'default': function() {}
// });
//
// Returns the result of the called function. To return this to create
// a chainable method, for example, pass in true as a second argument:
//
// var fn = overloadByTypes({...}, true);
function toType(object) {
return typeof object;
}
function overloadByTypes(signatures, returnFlag) {
return function method() {
var signature = Array.prototype.map.call(arguments, toType).join(' ');
var fn = signatures[signature] || signatures.default;
if (!fn) { throw new Error('overloadByTypes: No function for type signature "' + signature + '" and no "default" defined.'); }
var result = fn.apply(this, arguments);
return returnFlag ? this : result ;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment