l0bsterssg

node.js static responsive blog post generator
Log | Files | Refs | README

index.js (2231B)


      1 var wordwrap = module.exports = function (start, stop, params) {
      2     if (typeof start === 'object') {
      3         params = start;
      4         start = params.start;
      5         stop = params.stop;
      6     }
      7     
      8     if (typeof stop === 'object') {
      9         params = stop;
     10         start = start || params.start;
     11         stop = undefined;
     12     }
     13     
     14     if (!stop) {
     15         stop = start;
     16         start = 0;
     17     }
     18     
     19     if (!params) params = {};
     20     var mode = params.mode || 'soft';
     21     var re = mode === 'hard' ? /\b/ : /(\S+\s+)/;
     22     
     23     return function (text) {
     24         var chunks = text.toString()
     25             .split(re)
     26             .reduce(function (acc, x) {
     27                 if (mode === 'hard') {
     28                     for (var i = 0; i < x.length; i += stop - start) {
     29                         acc.push(x.slice(i, i + stop - start));
     30                     }
     31                 }
     32                 else acc.push(x)
     33                 return acc;
     34             }, [])
     35         ;
     36         
     37         return chunks.reduce(function (lines, rawChunk) {
     38             if (rawChunk === '') return lines;
     39             
     40             var chunk = rawChunk.replace(/\t/g, '    ');
     41             
     42             var i = lines.length - 1;
     43             if (lines[i].length + chunk.length > stop) {
     44                 lines[i] = lines[i].replace(/\s+$/, '');
     45                 
     46                 chunk.split(/\n/).forEach(function (c) {
     47                     lines.push(
     48                         new Array(start + 1).join(' ')
     49                         + c.replace(/^\s+/, '')
     50                     );
     51                 });
     52             }
     53             else if (chunk.match(/\n/)) {
     54                 var xs = chunk.split(/\n/);
     55                 lines[i] += xs.shift();
     56                 xs.forEach(function (c) {
     57                     lines.push(
     58                         new Array(start + 1).join(' ')
     59                         + c.replace(/^\s+/, '')
     60                     );
     61                 });
     62             }
     63             else {
     64                 lines[i] += chunk;
     65             }
     66             
     67             return lines;
     68         }, [ new Array(start + 1).join(' ') ]).join('\n');
     69     };
     70 };
     71 
     72 wordwrap.soft = wordwrap;
     73 
     74 wordwrap.hard = function (start, stop) {
     75     return wordwrap(start, stop, { mode : 'hard' });
     76 };