Skip to content

Instantly share code, notes, and snippets.

@jauco
Created October 4, 2009 11:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jauco/201307 to your computer and use it in GitHub Desktop.
Save jauco/201307 to your computer and use it in GitHub Desktop.
Design by contract in javascript
//Design by contract function
function $contracted(pre, post, func){
return function(){
var paramsAsArray,
funcName,
retVal;
paramsAsArray = Array.slice(arguments)
funcName = func.toString().substr('function '.length);
funcName = funcName.substr(0, funcName.indexOf('('));//strip of everything, but the name
if (!pre.apply(this, paramsAsArray)){
console.error("pre condition failed for '",func,"' with: ",paramsAsArray);
throw "pre condition failed for '"+ funcName+"'";
} else {
retVal = func.apply(this, paramsAsArray);
if (!post(retVal)){
console.error("post condition failed for '",func,"'. It returned '",retVal,"' with: ",paramsAsArray);
throw "post condition failed for '"+ funcName+"'";
}
return retVal;
}
}
}
//Example:
var doSomething = $contracted(
function pre(a,b,c) b > 0, //javascript 1.8 needed for the fancy lambda syntax. else write: function pre(a,b,c){return b>0 }
function post(r) r > 0,
function doSomething(a,b,c){
return a + (c / b);
}
);
doSomething(1,2,3);
doSomething(0,0,0);
doSomething(0,3,0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment