Last active
August 29, 2015 14:27
-
-
Save stephband/e30cbb43cff122403d05 to your computer and use it in GitHub Desktop.
Overload a function according to the types of arguments passed in
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
// 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