Skip to content

Instantly share code, notes, and snippets.

@sebinsua
Created November 3, 2022 20:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebinsua/763998bee8efb3d7e1d04ec53dea5349 to your computer and use it in GitHub Desktop.
Save sebinsua/763998bee8efb3d7e1d04ec53dea5349 to your computer and use it in GitHub Desktop.
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"));
@sebinsua
Copy link
Author

sebinsua commented Nov 9, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment