Function overloading

A sample implementation of function overloading

by Arnaud Buchholz

JavaScript

function overload () {
	var overloads = [].slice.call(arguments, 0);
  return function () {
  	var numberOfParameters = arguments.length,
        selectedOverload;
    overloads.every(function (overloadFunction) {
    	if (overloadFunction.length === numberOfParameters) {
      	selectedOverload = overloadFunction;
        return false;
      }
      return true;
    });
    if (selectedOverload) {
    	return selectedOverload.apply(this, arguments);
    } else {
    	throw "No overload found";
    }
  };
}

// Minimalist testing framework

function assert(condition) {
	if (!condition) {
  	throw "Assertion failed";
  }
}

function it(label, callback) {
	var line = document.createElement("div"),
  	  span;
  line.appendChild(document.createTextNode(label + ":"));
  span = line.appendChild(document.createElement("span"));
  try {
  	callback();
    span.style.color = "green";
    span.innerHTML = "OK";
  } catch (e) {
    span.style.color = "red";
    span.innerHTML = "KO";
  }
  document.body.appendChild(line);
}

// Test cases

var result = overload(function () {
	return "no result";
}, function (a) {
	return a;
}, function (a, b) {
	return a + b;
});

it("returns no result with no parameter", function () {
	assert(result() === "no result");
});

it("returns the parameter with only one parameter", function () {
	assert(result(1) === 1);
});

it("returns the sum of parameters with two parameters", function () {
	assert(result(1, 2) === 3);
});

it("fails if more than two parameters", function () {
	var exceptionCaught;
	try {
  	result(1, 2, 3);
  } catch (e) {
  	exceptionCaught = e;
  }
	assert(undefined !== exceptionCaught);
});