Skip to content

Instantly share code, notes, and snippets.

@mattparker
Created March 18, 2014 20:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattparker/9629012 to your computer and use it in GitHub Desktop.
Save mattparker/9629012 to your computer and use it in GitHub Desktop.
pre and post conditions in js
// 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