Last active
January 24, 2023 16:34
-
-
Save FrancoAguilera/58ebbb73ea078092031777ea088c7080 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
const compress = (str) => { | |
if (str.length < 2) { | |
return str; | |
} | |
const arr = str.split(""); | |
let oputput = []; | |
let count = 1; | |
for (let i = 0; i < arr.length; i++) { | |
if (arr[i] === arr[i + 1]) { | |
count += 1; | |
} else { | |
const char = count === 1 ? `${arr[i]}` : `${arr[i]}x${count}`; | |
oputput.push(char); | |
count = 1; | |
} | |
} | |
return oputput.join(""); | |
}; | |
console.log(compress("aaaaaabbbcaaa")); // ax4ca |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment