Skip to content

Instantly share code, notes, and snippets.

@mappum
Last active August 29, 2015 14:03
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 mappum/19b5f12edd001b33a72f to your computer and use it in GitHub Desktop.
Save mappum/19b5f12edd001b33a72f to your computer and use it in GitHub Desktop.
Type-checking annotation in vanilla Javascript
// It's possible to add your own quasi language constructs in JS using comments and Function#toString.
// (Doesn't survive minification)
// (You might need to modularize the execution of the annotations)
function checkType(f) {
return function(a) {
var type = f.toString().match(/\/\/(.*)\n/)[1].trim();
if(type !== typeof(a)) throw new Error('Invalid type');
return f(a);
}
}
var halve = checkType(function(n) {
// number
return n / 2;
});
halve(4); // returns 2
halve('string'); // emits error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment