7 ms·
That's a really smart hack, I didn't realize comments were included in the output of Function#toString. You could do other cool things, e.g. an annotation for t
by mappum 12y ago
That's a really smart hack, I didn't realize comments were included in the output of Function#toString. You could do other cool things, e.g. an annotation for type checking:
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
- tlrobinson 12y agoI didn't realize comments were included in the output of Function#toString Probably because sometimes they're not, depending on the JavaScript engine (though perhaps all of the major modern browsers do)
- mofle 12y agoThe following browsers return comments: - Latest Chrome - Firefox >=17 - Safari >=4 - Opera >=9 - Internet Explorer >=6 From: https://github.com/sindresorhus/multiline#compatibility https://github.com/sindresorhus/multiline#compatibility
- coldtea 12y agoNot just "Latest Chrome". Chrome has been doing it for at least 2 years. I know, because I'm using it with it.
- manojlds 12y agoI think Chrome is mentioned as "Latest Chrome" because: 1) There have been so many versions and not easy to know what came when. 2) Most people get updated to Chrome latest automatically without any fuss.
- mofle 12y agoThat's correct. Chrome is practically versionless.
- msujaws 12y agoIn fact, (2) is not as true as it used to be. This graph, http://cdn.arstechnica.net/wp-content/uploads/2014/07/chrome-2014-06.png http://cdn.arstechnica.net/wp-content/uploads/2014/07/chrome..., shows that about 6-7 percent of worldwide browsers are out-of-date Chrome installs, and the trend is for that to grow. From http://arstechnica.com/information-technology/2014/07/windows-8-x-internet-explorer-both-flatline-in-june/ http://arstechnica.com/information-technology/2014/07/window...
- igl 12y agoClosure Compiler.