Last active
September 17, 2015 11:18
-
-
Save saltukalakus/6bce3630d1c76e56f785 to your computer and use it in GitHub Desktop.
Function overloading
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
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