Home

Run Length

Question

Have the function RunLength(str) take the str parameter being passed and return a 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.

Solution

function RunLength(str) { // handle base case if (str.length === 1) { return `1${str}`; } // iterate through str, set current index and count number until change in char let res = ''; let original = str.toLowerCase(); let curLetter = original[0]; let count = 1; for (let i = 1; i < original.length; i++) { if (original[i] === curLetter) { count++; } else { res += `${count}${curLetter}`; curLetter = original[i]; count = 1; } // handle final letter if (i === original.length - 1) { res += `${count}${curLetter}`; } } // code goes here return res; }