wrap.js 794 B

123456789101112131415161718192021222324252627
  1. 'use strict';
  2. /**
  3. * @param {string} msg The message to wrap
  4. * @param {object} opts
  5. * @param {number|string} [opts.margin] Left margin
  6. * @param {number} opts.width Maximum characters per line including the margin
  7. */
  8. module.exports = (msg, opts = {}) => {
  9. const tab = Number.isSafeInteger(parseInt(opts.margin))
  10. ? new Array(parseInt(opts.margin)).fill(' ').join('')
  11. : (opts.margin || '');
  12. const width = opts.width;
  13. return (msg || '').split(/\r?\n/g)
  14. .map(line => line
  15. .split(/\s+/g)
  16. .reduce((arr, w) => {
  17. if (w.length + tab.length >= width || arr[arr.length - 1].length + w.length + 1 < width)
  18. arr[arr.length - 1] += ` ${w}`;
  19. else arr.push(`${tab}${w}`);
  20. return arr;
  21. }, [ tab ])
  22. .join('\n'))
  23. .join('\n');
  24. };