Skip to content

Instantly share code, notes, and snippets.

@FrancoAguilera
Last active January 24, 2023 16:34
Show Gist options
  • Save FrancoAguilera/58ebbb73ea078092031777ea088c7080 to your computer and use it in GitHub Desktop.
Save FrancoAguilera/58ebbb73ea078092031777ea088c7080 to your computer and use it in GitHub Desktop.
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