Skip to content

Instantly share code, notes, and snippets.

@odykyi
Last active October 10, 2019 12:19
Show Gist options
  • Save odykyi/05b31fb476dbd5bf7326736f19010c60 to your computer and use it in GitHub Desktop.
Save odykyi/05b31fb476dbd5bf7326736f19010c60 to your computer and use it in GitHub Desktop.
Js Javascript / Run-length encoding algorithm / RLE encode encoding
function encode(code) {
if (!code) return '';
let encode = '';
for (let i = 0; i < code.length; i++) {
let count = 1;
for (let j = i; j < code.length; j++) {
if (code[i] !== code[j+1]) break;
count++;
i++;
}
encode += count === 1 ? code[i] : count + code[i];
}
return encode
}
encode("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB"); // "12WB12W3B24WB"
encode("AABBBCCCC"); // "2A3B4C"
encode(""); // ""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment