index.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*!
  2. * word-wrap <https://github.com/jonschlinkert/word-wrap>
  3. *
  4. * Copyright (c) 2014-2023, Jon Schlinkert.
  5. * Released under the MIT License.
  6. */
  7. function trimEnd(str) {
  8. let lastCharPos = str.length - 1;
  9. let lastChar = str[lastCharPos];
  10. while(lastChar === ' ' || lastChar === '\t') {
  11. lastChar = str[--lastCharPos];
  12. }
  13. return str.substring(0, lastCharPos + 1);
  14. }
  15. function trimTabAndSpaces(str) {
  16. const lines = str.split('\n');
  17. const trimmedLines = lines.map((line) => trimEnd(line));
  18. return trimmedLines.join('\n');
  19. }
  20. module.exports = function(str, options) {
  21. options = options || {};
  22. if (str == null) {
  23. return str;
  24. }
  25. var width = options.width || 50;
  26. var indent = (typeof options.indent === 'string')
  27. ? options.indent
  28. : ' ';
  29. var newline = options.newline || '\n' + indent;
  30. var escape = typeof options.escape === 'function'
  31. ? options.escape
  32. : identity;
  33. var regexString = '.{1,' + width + '}';
  34. if (options.cut !== true) {
  35. regexString += '([\\s\u200B]+|$)|[^\\s\u200B]+?([\\s\u200B]+|$)';
  36. }
  37. var re = new RegExp(regexString, 'g');
  38. var lines = str.match(re) || [];
  39. var result = indent + lines.map(function(line) {
  40. if (line.slice(-1) === '\n') {
  41. line = line.slice(0, line.length - 1);
  42. }
  43. return escape(line);
  44. }).join(newline);
  45. if (options.trim === true) {
  46. result = trimTabAndSpaces(result);
  47. }
  48. return result;
  49. };
  50. function identity(str) {
  51. return str;
  52. }