wrap.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. // Wrap
  2. // wraps a string by a certain width
  3. var makeString = require('./helper/makeString');
  4. module.exports = function wrap(str, options){
  5. str = makeString(str);
  6. options = options || {};
  7. var width = options.width || 75;
  8. var seperator = options.seperator || '\n';
  9. var cut = options.cut || false;
  10. var preserveSpaces = options.preserveSpaces || false;
  11. var trailingSpaces = options.trailingSpaces || false;
  12. var result;
  13. if(width <= 0){
  14. return str;
  15. }
  16. else if(!cut){
  17. var words = str.split(' ');
  18. var current_column = 0;
  19. result = '';
  20. while(words.length > 0){
  21. // if adding a space and the next word would cause this line to be longer than width...
  22. if(1 + words[0].length + current_column > width){
  23. //start a new line if this line is not already empty
  24. if(current_column > 0){
  25. // add a space at the end of the line is preserveSpaces is true
  26. if (preserveSpaces){
  27. result += ' ';
  28. current_column++;
  29. }
  30. // fill the rest of the line with spaces if trailingSpaces option is true
  31. else if(trailingSpaces){
  32. while(current_column < width){
  33. result += ' ';
  34. current_column++;
  35. }
  36. }
  37. //start new line
  38. result += seperator;
  39. current_column = 0;
  40. }
  41. }
  42. // if not at the begining of the line, add a space in front of the word
  43. if(current_column > 0){
  44. result += ' ';
  45. current_column++;
  46. }
  47. // tack on the next word, update current column, a pop words array
  48. result += words[0];
  49. current_column += words[0].length;
  50. words.shift();
  51. }
  52. // fill the rest of the line with spaces if trailingSpaces option is true
  53. if(trailingSpaces){
  54. while(current_column < width){
  55. result += ' ';
  56. current_column++;
  57. }
  58. }
  59. return result;
  60. }
  61. else {
  62. var index = 0;
  63. result = '';
  64. // walk through each character and add seperators where appropriate
  65. while(index < str.length){
  66. if(index % width == 0 && index > 0){
  67. result += seperator;
  68. }
  69. result += str.charAt(index);
  70. index++;
  71. }
  72. // fill the rest of the line with spaces if trailingSpaces option is true
  73. if(trailingSpaces){
  74. while(index % width > 0){
  75. result += ' ';
  76. index++;
  77. }
  78. }
  79. return result;
  80. }
  81. };