Skip to content

Instantly share code, notes, and snippets.

@devinrhode2
Last active November 19, 2018 21:14
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 devinrhode2/4166074 to your computer and use it in GitHub Desktop.
Save devinrhode2/4166074 to your computer and use it in GitHub Desktop.
Working on a typeCheck function
function postTweet(tweet /*string*/, from /*string*/) {
typeCheck(arguments);
}
postTweet('string', 'asdf');
postTweet('string', 222); //TypeError! run in console to see a nice error message!
function typeCheck(a) {
var newArr = [].slice.call(a);
var types = [];
var f = a.callee.toString();
f = f.substring(f.indexOf('(') + 1, f.indexOf(')') );
f = f.split(',');
f.forEach(function forEachArgStatement(s) {
var start = s.indexOf('/*') + 2;
types.push({
name: s.substring(0, start - 2),
type: s.substring(start, s.indexOf('*/', start) )
});
});
//Might want to:
/*
try {
args.callee = typeCheck.caller;
} catch( _ ) { }
*/
// From html5 boilerplate: https://github.com/h5bp/html5-boilerplate/commit/5370479476dceae7cc3ea105946536d6bc0ee468#js/plugins.js
var callerName = a.callee.name;
newArr.forEach(function forEachArg(arg, index){
if (typeof arg !== types[index].type) {
console.log('Bad arg:', arg);
throw new TypeError(callerName + ' expects arg ' + (index+1) + ' `' + types[index].name.trim() + '` to be `' + types[index].type + '` but is `' + typeof arg + '` Bad arg above.');
}
});
}
@devinrhode2
Copy link
Author

Leave a comment!

@chrixian
Copy link

WHAT ARE YOU, SOME KIND OF WIZARD?

@devinrhode2
Copy link
Author

perhaps. ^_^

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment