3 ms·
Here's a simple implementation without sweet.js: var inlineTest = function(fn, tests) { (tests || []).forEach(function(test){ if (fn.apply(this, te
by cj 13y ago
Here's a simple implementation without sweet.js:
var inlineTest = function(fn, tests) {
(tests || []).forEach(function(test){
if (fn.apply(this, test[0]) !== test[1]) {
throw new Error('Failed inline unit test with args: ' + test[0]);
}
});
return fn;
};
var square = inlineTest(function(n){
return n * n;
}, [
[[2],4], // [[arrayOfArguments], expectedResult]
[[3],5] // <-- This test will throw an error
]);
EDIT: Change fn.call to fn.apply
- tiles 13y agoNice. If you wanted to go even more inline: 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 );
- sergimansilla 13y agoCool, 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.
- camus2 13y agoyou just gave me an idea for a "typechecking" api.thanks.
- jordanwallwork 13y agoI 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-overloading-in-javascript/ http://jordanwallwork.co.uk/2013/01/faking-typed-function-ov...