// Wrap
// wraps a string by a certain width
makeString = require('./helper/makeString');
module.exports = function wrap(str, width, seperator, cut){
str = makeString(str);
width = width || 75;
seperator = seperator || '\n';
cut = cut || false;
if(width <= 0){
return str;
}
else if(!cut){
words = str.split(" ");
for(var i = 0; i < words.length - 1; i++){
//preserve the spaces for all words except the last one
words[i] = words[i] + " ";
}
// now words looks like ['firstWord ', 'secondWord ', 'lastWord']
result = "";
current_column = 0;
while(words.length > 0){
// if adding the next word would cause this line to be longer than width...
if(words[0].length + current_column > width){
//start a new line if this line is not already empty
if(current_column > 0){
//start new line
result += seperator;
current_column = 0;
}
}
result += words[0];
current_column += words[0].length;
words.shift();
}
return result;
}
else {
index = 0;
result = "";
// walk through each character and add seperators where appropriate
while(index < str.length){
if(index % width == 0 && index > 0){
result += seperator;
}
result += str.charAt(index);
index++;
}
return result;
}
}; |