Last active
November 1, 2020 13:05
-
-
Save PanJarda/3ae03c23ae7919975be9547788822f38 to your computer and use it in GitHub Desktop.
Contractual programming in js concept
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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