Last active
August 29, 2015 14:03
-
-
Save mappum/19b5f12edd001b33a72f to your computer and use it in GitHub Desktop.
Type-checking annotation in vanilla Javascript
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
// 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