Skip to content

Instantly share code, notes, and snippets.

@thinkaxelthink
Created September 1, 2023 20:49
Show Gist options
  • Select an option

  • Save thinkaxelthink/94a8839e77f739fc11b46abf526433c5 to your computer and use it in GitHub Desktop.

Select an option

Save thinkaxelthink/94a8839e77f739fc11b46abf526433c5 to your computer and use it in GitHub Desktop.
wonder compress first draft
function compress(param) {
const charsCount = {};
let lastCharProcessed = null;
let result = [];
param.split("").forEach((s, idx, arr) => {
if (!charsCount[s]) {
charsCount[s] = 1;
} else {
charsCount[s] += 1;
}
if (lastCharProcessed !== s) {
result.push(lastCharProcessed);
if (charsCount[lastCharProcessed] > 1) {
result.push(charsCount[lastCharProcessed]);
}
charsCount[lastCharProcessed] = 0;
}
if (idx === arr.length - 1) {
result.push(s);
if (charsCount[s] > 1) result.push(charsCount[s]);
}
lastCharProcessed = s;
});
return result.join("");
}
console.log("aabbccc", compress("aabbccc"), compress("aabbccc") === "a2b2c3");
console.log("abcd", compress("abcd"), compress("abcd") == "abcd");
console.log("abbaac", compress("abbaac"), compress("abbaac") == "ab2a2c");
console.log("abbbbbbbbbbbb", compress("abbbbbbbbbbbb"), compress("abbbbbbbbbbbb") == "ab12");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment