Last active
October 10, 2019 12:19
-
-
Save odykyi/05b31fb476dbd5bf7326736f19010c60 to your computer and use it in GitHub Desktop.
Js Javascript / Run-length encoding algorithm / RLE encode encoding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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