Code coverage report for lib/algorithms/1-strings/escape.js

Statements: 94.12% (16 / 17)      Branches: 83.33% (5 / 6)      Functions: 100% (1 / 1)      Lines: 100% (16 / 16)      Ignored: none     

All files » lib/algorithms/1-strings/ » escape.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  1 3 3 3     3   3 18     3   69 60   9 9 9 9       3     1
//1.4) Write a method to replace all spaces with '%20'.
function escape(sentence) {
	Iif (typeof sentence !== "string") throw "The given sentence is not a string";
	var padding = 0;
	var length = sentence.length;
 
	//turn string into array
	sentence = sentence.split("");
 
	for(var i = length - 1; (i >= 0) && (sentence[i] === ' '); i--) {
		padding++;
	}
 
	for(var i = length - padding - 1; i >= 0; i--) {
 
		if(sentence[i] !== ' ') {
			sentence[i + padding] = sentence[i];
		} else {
			sentence[i + padding -2] = '%';
			sentence[i + padding-1] = '2';
			sentence[i + padding] = '0';
			padding = padding - 2;
		}
	}
 
	return sentence.join("");
};
 
module.exports = escape;