Skip to content

Instantly share code, notes, and snippets.

@nicholasaiello
Last active October 14, 2017 21:48
Show Gist options
  • Save nicholasaiello/6ff49f278d0096d68e60d94bf98a9878 to your computer and use it in GitHub Desktop.
Save nicholasaiello/6ff49f278d0096d68e60d94bf98a9878 to your computer and use it in GitHub Desktop.
// Given a string "aaabbbccdeff", compress it, = "a3b3c2def2"
const input = "aaabbbccdeff";
function compressWord(str = '') {
const size = (str || '').length;
// edge cases
if (size < 2) {
return str;
} else if (size === 2) {
if (str.charAt(0) === str.charAt(1)) {
return str.charAt(0) + '2';
} else {
return str;
}
}
// count char occurrences
let i = 1;
const ch = str.charAt(0);
while (i < str.length && ch === str.charAt(i)) {
i++;
}
return str.substring(0, 1)
+ (i > 1 ? i : '')
+ compressWord(str.substring(i));
}
console.log(compressWord(input));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment