Functions overloader

Attach multiple methods of the same name but with varying number of parameters for function overloading

by Amy L

JavaScript

function addMethod (obj, name, fn) {
    var oldFn = obj[name];
    obj[name] = function() {
        if (fn.length === arguments.length) {
            return fn.apply(this, arguments);
        } else if (name in obj) {
            return oldFn.apply(this, arguments);
        }
    };
};

var cart = {
    items: []
};
addMethod(cart, 'add', function(name) {
    this.items.push({ name: name, color: 'none', weight: 0 });
});
addMethod(cart, 'add', function(name, weight) {
    this.items.push({  name: name, color: 'none', weight: weight });
});
addMethod(cart, 'add', function(name, weight, color) {
    this.items.push({ name: name, color: color, weight: weight });
});

// test it out
cart.add('air');
cart.add('apple', 100);
cart.add('banana', 250);
console.log(cart.items);