I was reading a post yesterday about function overloading in javascript, and the suggested solution had quite a performance overhead when used with multiple signatures.
In addition, it only used the number of arguments, and not their types and order to distinguish between the signatures.
For some reason I woke up early this morning with a solution to this.
The following code will do all of the above and has the same overhead for all number of signatures.
//returns an overloadable method
Function.CreateOverloaded = function(){
var overloads = [];
//creates the overloaded method
var func = function(){
var sign = [];
for (var i=0;i < arguments.length; i++) {
sign.push(typeof arguments[i]);
}
sign = sign.join();
var func = overloads["(" + sign + ")"];
if (!func) {throw "No matching signature";}
return func.apply(this, arguments);
};
//method for adding a function with a spesific signature
func.AddSignature = function(func, sign){
if (overloads["(" + sign + ")"]){throw "Duplicate signature"};
overloads["(" + sign + ")"] = func;
};
return func;
}
To test it you can use the following code
var myFunc = Function.CreateOverloaded();
myFunc.AddSignature(function(){
alert("test1");
}, "");
myFunc.AddSignature(function(var){
alert(var);
}, "string");
myFunc.AddSignature(function(integer){
alert(integer + "x 5 = " + (integer * 5));
}, "number");
myFunc.AddSignature(function(int1, int2){
alert(int1 * int2);
}, "number,number");
myFunc.AddSignature(function(string, int){
alert(string + " equals " + int);
}, "string,number");
myFunct();
myFunc("test2")
myFunc(3);
myFunc(3, 5);
myFunc("five", 5);
My name is Øyvind Sean Kinsey and I am currently a software engineer at