Code coverage report for master/wrap.js

Statements: 100% (31 / 31)      Branches: 100% (18 / 18)      Functions: 100% (1 / 1)      Lines: 100% (31 / 31)      Ignored: none     

All files » master/ » wrap.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55      1   1 11 11 11 11 11 1   10 9 9   13       9 9   9   22   9   8 8     22 22 22   9       1 1   1 10 4   10 10   1    
// 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;
	}
};