Skip to content

Instantly share code, notes, and snippets.

@PanJarda
Last active November 1, 2020 13:05
Show Gist options
  • Save PanJarda/3ae03c23ae7919975be9547788822f38 to your computer and use it in GitHub Desktop.
Save PanJarda/3ae03c23ae7919975be9547788822f38 to your computer and use it in GitHub Desktop.
Contractual programming in js concept
const DEV = true;
function contract(conditions) {
if (DEV) {
return function(fn) {
return function() {
if (!conditions.pre.apply(null, arguments)) {
throw 'precondition failed on ' + fn.name
}
var result = fn.apply(null, arguments);
if (!conditions.post(result)) {
throw 'postcondition failed'
}
return result
}
}
}
return function(fn) {
return fn;
};
}
(function test() {
function testedFunction(param1, param2) {
return param1 + param2;
}
var testedFunction = contract({
pre: function(param1, param2) {
return (typeof param1 === 'number'
&& typeof param2 === 'number')
},
post: function(result) {
return result < 12;
}
})(testedFunction);
var result = testedFunction(1, 2);
console.log(result);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment