Last active
November 19, 2018 21:14
-
-
Save devinrhode2/4166074 to your computer and use it in GitHub Desktop.
Working on a typeCheck function
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
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.'); | |
} | |
}); | |
} |
WHAT ARE YOU, SOME KIND OF WIZARD?
perhaps. ^_^
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Leave a comment!