Last active
October 14, 2017 21:48
-
-
Save nicholasaiello/6ff49f278d0096d68e60d94bf98a9878 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
// 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