I'm solving the following coderbyte.com challenge:
Using the JavaScript language, have the function RunLength (str) take the str parameter being passed and return to the compressed version of the string using the Run-length encoding algorithm. This algorithm works by taking the occurrence of each repeating character and outputting that number along with a single character of the repeating sequence. For example: "wwwggopp" would return 3w2g1o2p. The string will not contain any numbers, punctuation, or symbols.
To do the RunLength algorithm, I wrote the following code:
function RunLength(str) {
str = str.split("");
var counter = 1;
for (var i=1; i<=str.length; i++) {
if (str[i] === str[i-1]) {
counter ++;
} else {
str.splice(i-1, counter-1, counter.toString());
counter = 1;
}
}
return str
}
The idea was to insert the counter variable with splice, which counts how many times a letter was repeated after each of the repeated letters, and remove the occurrences of the repeated letter.