Monday, November 12, 2012

heredoc in javascript

Javascript doesn't have built-in  "heredoc" operator or feature. So, if we need it, we have to implement it by ourself. Here is one of possible way to implement heredoc-style functionality.

1. To prevent javascript from checking syntax and issuing errors we create desired string as a comment within a function body:

var foo = function(){/*
blah blah blah
*/};  

2. Use built-in "toString()" function to extract this string:

var bar = foo.toString();

But toString() returns everything, not only function body:
"function (){/*blah blah blah/*}"
So, we need to extract only the part we need. I can suggest 2 possible ways:

a) foo.toString().slice(14, -3);
b) foo.toString().split(/\n/).slice(1, -1).join('\n');

if you select the second version, you must start and end your string with new line:
function (){/*
blah
blah blah
*/}

Generic functions:
1)
function heredoc(fn) {
return fn.toString().slice(14, -3);
}

2)
function heredoc(fn) {

return fn.toString().split(/\n/).slice(1, -1).join('\n');
}


There is no difference in performance between these two solutions. I prefer the first one as it looks  more simple, and short strings can be written in one line. But it matter of test.

Usage:

var foo = function(){/*
blah
blah blah

*/}; 


var bar = heredoc(foo);



console.log(bar); // blah 
                            blah blah

------------------------------------------------------------------------------------

Enjoy.
var zzz = function(){/*
var xxx
 = 
 
var zzz = function(){/*
var xxx
 = 
 'aaa';*/};var zzz = function(){/*
var xxx
 = 
 'aaa';*/};