overload.js

Function overloading or method overloading is a feature found in various programming languages such as Ada, C++, C#, D, and Java, that allows creating several methods with the same name which differ from each other in the type of the input and the output of the function. It is simply defined as the ability of one function to perform different tasks.

Javascript has always lacked this ability and though there are many hacks and workarounds for this, none of them provide a clear and concise method for overloading.

This function makes it possible to overload your home-made functions as well as class methods and even native functions in a simple way.

Usage

Functions are overloaded by calling
myFunction = overload(myFunction, types, newFunction);
with the following parameters:

myFunction

· The function to be overloaded.

types

· An array of strings describing the argument types that the function will be overloaded for. The argument types can be of the form "String", "Array", "MyClass" etc. or they can each be a list of || separated types (eg. "String || Number"). You can also use "*" as an argument type indicating that anything can be passed to it.
note: The array can also contain validating functions that take a single argument and return true if it's valid.

newFunction

· The function to be used when arguments of the correct types are passed.

Example usage
function area(r){
    return Math.PI*r*r; // area of a circle with radius r
}

area = overload(area, ['Number', 'Number'], function(l, w){
    return l*w; // area of a rectangle given length + width
});

area(2);    // returns 4*pi
area(3, 4); // returns 12

For more examples, check out the Demo page

The code

Just include the following function in your project to enable function overloading

function overload(original, matches, fn){
    return function(){
        if(matches.length == arguments.length){
            for(var i = 0, type; i < matches.length; i++){
                if(typeof matches[i] == "string" && typeof arguments[i] != "undefined" && arguments[i] != null){
                    type = (/function (.{1,})\(/).exec(arguments[i].constructor.toString())[1];
                    if(matches[i] != "*" && ("||"+matches[i].replace(/ /g, "")+"||").split("||"+type+"||").length <= 1) break;
                } else if(typeof matches[i] == "function"){
                    if(!matches[i](arguments[i])) break;
                } else break;
            }
            if(i == matches.length) return fn.apply(this, arguments);
        }
        return original.apply(this, arguments);
    }
}

Contribute

View the project on Github. Feel free to fork or contribute!