Overload example
by Arnaud Buchholz
CSS
.ok:after {
display: inline-block;
width: 1rem;
color: green;
content: "✓";
}
.ko:after {
display: inline-block;
width: 1rem;
color: red;
content: "✗";
}
JavaScript
function it(label, callback) {
var line = document.createElement("div"),
status,
succeeded;
status = line.appendChild(document.createElement("span"));
line.appendChild(document.createTextNode(label));
try {
succeeded = callback();
} catch (e) {
succeeded = false;
}
status.className = succeeded ? "ok" : "ko";
return document.body.appendChild(line);
}
function inc (value, step) {
return value + step;
}
it("inc(0, 2) === 2", function () {
return inc(0, 2) === 2;
});
Function.prototype.overload = function (newVersion) {
var currentVersion = this;
return function () {
if (arguments.length === newVersion.length) {
return newVersion.apply(this, arguments);
}
return current.apply(this, arguments);
}
};
it("exposes an overlad method accepting one parameter", function () {
return "function" === typeof inc.overload
&& 1 === inc.overload.length;
});
it("returns a function that accepts the two signatures", function () {
var overloaded = inc.overload(function (value) {
return inc(value, 1);
});
return "function" === typeof overloaded && 2 === overloaded(1);
});