Created
March 18, 2014 20:36
-
-
Save mattparker/9629012 to your computer and use it in GitHub Desktop.
pre and post conditions in js
This file contains 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
// this: https://twitter.com/raganwald/status/445938910808391680 | |
// Wrap a function f (which accepts two arguments, and b) to enforce | |
// preconditions (if I understand them correctly) are guards on | |
// parameter values | |
// You can also optionally add a postcondition afterwards | |
// though it'd be nicer to add this in the main preCondition function really | |
// conditionA and conditionB are boolean functions | |
// f is our actual function | |
preCondition = function (f, conditionA, conditionB) { | |
var conditionedF = function (a, b) { | |
var returnValue; | |
if (conditionA(a) && conditionB(b)) { | |
returnValue = f(a,b); | |
if (conditionedF.postCondition) { | |
if (conditionedF.postCondition(returnValue)) { | |
return returnValue; | |
} | |
throw "WRONG AGAIN!"; | |
} | |
return returnValue; | |
} | |
throw "WRONG!!!"; | |
} | |
return conditionedF; | |
} | |
// And this is an example condition function | |
IntRange = function (low, high) { | |
return function (val) { | |
return (val > low && val < high); | |
} | |
}; | |
// so in use: | |
var myLimitedAddingFunction = preCondition( function (a, b) {return a+b;}, IntRange(0, 10), IntRange(-5, 0)); | |
myLimitedAddingFunction(0, 0); | |
// > WRONG!!! | |
myLimitedAddingFunction(2, -3); | |
// > -1 | |
// and optionally: | |
myLimitedAddingFunction.postCondition = IntRange(-4, -2); | |
myLimitedAddingFunction(2, -3); | |
// > WRONG AGAIN! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment