Created
September 6, 2013 10:33
-
-
Save Witiko/6462170 to your computer and use it in GitHub Desktop.
A simple library adding the function overloading capability to javascript
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
Function.overload = function(f) { | |
if(!(f instanceof Function)) return; | |
var _$ = function() { | |
var $ = [arguments, , this, _$._overloads], | |
_ = function(type, index) { | |
if(type instanceof Array) return type.some(function(type) { | |
return _(type, index); | |
}); | |
if(!($[0][index] instanceof Object)) | |
$[0][index] = Object($[0][index]); | |
if((typeof type === "string" && | |
typeof $[0][index] === type) || | |
(type instanceof String && | |
typeof $[0][index] === type.valueOf()) || ( | |
$[0][index] instanceof Object && | |
type instanceof Function && | |
$[0][index] instanceof type)) return true; | |
}; | |
return !$[3].args.some(function(overload, index) { | |
if(overload.length === $[0].length && (!$[0].length || overload.every(_))) | |
return !void($[1] = $[3].functions[index].apply($[2], $[0])); | |
}) && $[3].default?$[3].default.apply($[2], $[0]):$[1]; | |
}; | |
_$._overloads = { | |
args: [Array.prototype.slice.call(arguments, 1)], | |
functions: [f] | |
}; | |
return _$; | |
}; | |
Function.prototype.overload = function(f) { | |
if(!this._overloads || !(f instanceof Function)) return; | |
this._overloads.args.unshift(Array.prototype.slice.call(arguments, 1)); | |
this._overloads.functions.unshift(f); | |
}; | |
Function.prototype.noSuchOverload = function(f) { | |
if(!this._overloads) return; | |
this._overloads.default = f; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment