-
-
Save sebinsua/763998bee8efb3d7e1d04ec53dea5349 to your computer and use it in GitHub Desktop.
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 encodeRLE(str) { | |
let buffer = ""; | |
let currentChar; | |
let count = 0; | |
for (let char of str) { | |
if (char !== currentChar) { | |
if (currentChar && count > 0) { | |
buffer += `${currentChar}${count > 1 ? String(count) : ""}`; | |
} | |
currentChar = char; | |
count = 1; | |
} else { | |
currentChar = char; | |
count++; | |
} | |
} | |
if (currentChar && count > 0) { | |
buffer += `${currentChar}${count > 1 ? String(count) : ""}`; | |
} | |
return buffer; | |
} | |
const isNumber = (char) => | |
char === "0" || | |
char === "1" || | |
char === "2" || | |
char === "3" || | |
char === "4" || | |
char === "5" || | |
char === "6" || | |
char === "7" || | |
char === "8" || | |
char === "9"; | |
function decodeRLE(str) { | |
let buffer = ""; | |
for (let index = 0; index < str.length; index++) { | |
const char = str[index]; | |
let numericIndex = index; | |
let number = ""; | |
while (isNumber(str[numericIndex + 1])) { | |
numericIndex++; | |
number += str[numericIndex]; | |
} | |
buffer += | |
number.length > 0 | |
? Array(parseInt(number, 10)).fill(char).join("") | |
: char; | |
// The if block isn't required but it makes the intent clearer. | |
if (index !== numericIndex) { | |
index = numericIndex; | |
} | |
} | |
return buffer; | |
} | |
console.log(encodeRLE("nooooooooothereisnootherway")); | |
console.log(decodeRLE("no9thereisno2therway")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See also: https://gist.github.com/sebinsua/97a8bca51188903d3199c1dad5694c96