You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
2.2 KiB

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