Skip to content

Instantly share code, notes, and snippets.

@lienista
Last active August 28, 2018 07:35
Show Gist options
  • Select an option

  • Save lienista/0f415579d896f5d460867c4a9f58ab00 to your computer and use it in GitHub Desktop.

Select an option

Save lienista/0f415579d896f5d460867c4a9f58ab00 to your computer and use it in GitHub Desktop.
Algorithms in Javascript: String Compression: Implement a method to perform basic string compression using the counts of repeated characters. For example, aabcccccaaa would become a2b1c5a3. If the compressed string would not become smaller than the original string, your method should return the original string.
const compressString = (s1) => {
let charMap = new Map();
for(let i=0; i<s1.length; i++){
charMap.set(s1[i], charMap.get(s1[i]) + 1 || 1);
}
let s = '',
mapKeys = charMap.keys(),
mapValues = charMap.values();
charMap.forEach(function(value, key, map){
s += key+value;
});
return s;
}
let a = 'aaabbccccaa';
console.log(compressString(a));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment