Skip to content

Instantly share code, notes, and snippets.

@saltukalakus
Last active September 17, 2015 11:18
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 saltukalakus/6bce3630d1c76e56f785 to your computer and use it in GitHub Desktop.
Save saltukalakus/6bce3630d1c76e56f785 to your computer and use it in GitHub Desktop.
Function overloading
test = require("tape");
function addMethod(object, name, fn){
object._store = object._store || {};
object._store[name] = object._store[name] || {};
object._store[name][fn.length] = fn;
object[name] = function() {
if(this._store[name][arguments.length])
return this._store[name][arguments.length].apply(this, arguments);
};
}
test("function overload", function(t){
var test_obj = {};
function add2(a,b) { return a+b };
function add3(a,b,c) { return a + b + c;}
addMethod(test_obj, "add", add2);
addMethod(test_obj, "add", add3);
t.equal(test_obj.add(1,2), 3, "add with 2 parameters");
t.equal(test_obj.add(1,2,3), 6, "add with 3 parameters");
t.end();
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment