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';*/};

4 comments:

  1. Time has caught up with this post. :)
    ES6 has template strings that support multiline/heredoc https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings

    ReplyDelete
  2. Casino - JamBase
    Play Casino 고양 출장안마 at 세종특별자치 출장샵 JAMBase! We offer over 100000 exciting games including Slots, Blackjack, Roulette, 양주 출장안마 Video Poker, Live Casino 평택 출장마사지 and so 경주 출장샵 much much more to our

    ReplyDelete