Function.prototype.where = function () {
var fn = this, tests = [].slice.apply(arguments);
(tests || []).forEach(function(test){
if (fn.call(this, test[0]) !== test[1]) {
throw new Error('Failed inline unit test with args: ' + test[0]);
}
});
return fn;
};
var square = function(n){
return n * n;
}.where(
[[2], 4], // [[arrayOfArguments], expectedResult]
[[3], 5] // <-- This test will throw an error
);
As I mention in the post though, mine is just a very simple macro. But it is enough to show how easy is to modify the language to fit different scenarios, such as testing. The macro could probably be expanded and improved a lot to fit much more complex scenarios like real Contract-based languages have.
Comments
Nice. If you wanted to go even more inline:
Cool, nice and clean :)
As I mention in the post though, mine is just a very simple macro. But it is enough to show how easy is to modify the language to fit different scenarios, such as testing. The macro could probably be expanded and improved a lot to fit much more complex scenarios like real Contract-based languages have.
you just gave me an idea for a "typechecking" api.thanks.
I wrote something like this once, never did anything with it but you might find it useful: http://jordanwallwork.co.uk/2013/01/faking-typed-function-ov...