Skip to content

Instantly share code, notes, and snippets.

@willkurt
Created February 16, 2011 20:12
Show Gist options
  • Save willkurt/830083 to your computer and use it in GitHub Desktop.
Save willkurt/830083 to your computer and use it in GitHub Desktop.
function overloading in JavaScript
//first some exmaples
//overload examples
var add = function(x,y){
return x+y;
}
overload("add",function(x,y,z){
return x+y+z;
});
overload("add",function(x,y,z,a){
return x+y+z+a;
});
/* example output
add(2,3)
>5
add(1,2,3)
>6
add(1,2,3,4)
>10
*/
//experiement adding arity based function overloading to javascript
//to do
var overload = function (namespace,name,def){
var loc = name + "_overloads";
//function has not been overloaded yet (may or may not already exist)
if(namespace[loc] == undefined) {
namespace[loc] = [];
//in case there was already a function name there
if(namespace[name] != undefined){
var old_func = namespace[name];
namespace[loc][old_func.length] = old_func;
//in the next step the original function will be over written
}
namespace[name] = function () {
var args = Array.prototype.slice.call(arguments);
return(
namespace[loc][arguments.length].apply(namespace,args)
);
};
}
//always the case
namespace[loc][def.length] = def;
};
//and of course all good programs should build off themselves as much as possible
//so we're using 'overload' to overload 'overload' with a sane default
overload(this,"overload",function(name,def){
overload(this,name,def);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment