Skip to content

Instantly share code, notes, and snippets.

@davidpp
Created October 13, 2015 20:10
Show Gist options
  • Save davidpp/247d7b93c9a326073a5b to your computer and use it in GitHub Desktop.
Save davidpp/247d7b93c9a326073a5b to your computer and use it in GitHub Desktop.
function fnDrawPrism(length, numWidth, intHeight){
//If any of these parameters are undefined, throw an error that lists the missing parameters.
// you can cut-and-past the declaration line to fill out 90% of the validation call:
validate(fnDrawPrism, length, numWidth, intHeight);
return length * numWidth * intHeight;
}
// this is cut-and-pasted into a file somewhere, edit to add more types or stricter checking
function validate(args){
var fn = args, actuals = [].slice.call(arguments, 1),
hung = {int: "Number", num: "Number", str: "String", arr: "Array",
obj: "Object", inp: "HTMLInputElement", dt: "Date", bln: "Boolean",
rx: "RegExp", frm: "HTMLFormElement", doc: "HTMLDocument"},
names = String(fn).split(/\s*\)\s*/)[0].split(/\s*\(\s*/)[1].split(/\s*\,\s*/),
mx = names.length, i = 0;
if(!fn.name)
fn.name = String(fn).split(/\s*(/)[0].split(/\s+/)[1] || 'anon';
for(i; i < mx; i++){
if(actuals[i] === undefined)
throw new TypeError("missing arg #" + i + " in " + fn.name + " - " + names[i]);
var hint = hung[names[i].split(/[A-Z]/)[0]],
got = toString.call(actuals[i]).split(/\W/)[2];
if(hint && got !== hint)
throw new TypeError("Wrong type in argument #" + i + " of " + fn.name + " - " + names[i] + ". Got: " + got + ", Expected: " + hint);
}
//try it out:
fnDrawPrism(1); //! missing arg #1 in fnDrawPrism - numWidth
fnDrawPrism(1,4); //! missing arg #2 in fnDrawPrism - intHeight
fnDrawPrism(1,2,3); // ok
fnDrawPrism(1,"2",3); //! Wrong type in argument #1 of fnDrawPrism - numWidth. Got: string, Expected: number
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment