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

Statements: 100% (26 / 26)      Branches: 100% (6 / 6)      Functions: 100% (2 / 2)      Lines: 100% (26 / 26)      Ignored: none     

All files » lib/algorithms/1-strings/ » compress.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    1 4 4 4 4   4 61   61   25     25 25 25 25       36     61 1       1     61 61   61 1       60 60   60       3     1
//1.5) Implement Basic string compression using # of repeated chars.
//     If compressed string is longer than original, use original.
var compress = function(toCompress) {
	var result = [];
	var current = '^';
	var numSame = 0;
	var index = -1;	//index of entry in result
 
	for (var j = 0; j < toCompress.length; j++) {
		var letter = toCompress[j];
 
		if (letter !== current) {
 
			index = index + numSame.toString().length;
 
			//reset numSame
			numSame = 1;
			result[index] = letter;
			index++;
			current = letter;
		}
		else
		{
			numSame++;
		}
 
		if ( ! writeNum( )) {
			return toCompress;
		}
	}
 
	function writeNum() {
 
		//dodgy, hacky, terrible use of (in-scope) globals
		var count = numSame.toString();
		var countSize = count.length;
 
		if(index + countSize + 1 > toCompress.length) {
			return false;
		}
		else
		{
			for(var i = 0; i < countSize; i++) {
				result[index + i] = count[i];
			}
			return true;
		}
	}
 
	return result.join("");
};
 
module.exports = compress;