Skip to content

Instantly share code, notes, and snippets.

@unilecs
Created October 3, 2017 20:54
Show Gist options
  • Save unilecs/93810f5924a67607c7fa8906759297d6 to your computer and use it in GitHub Desktop.
Save unilecs/93810f5924a67607c7fa8906759297d6 to your computer and use it in GitHub Desktop.
Compress string: ABBCCCD -> AB2C3D
function CompressString(str) {
let acc = 0;
let char;
let result = str.split('').reduce((r, currentValue, index, arr) => {
if (currentValue != arr[index-1]) {
if (char) {
r += ((acc > 1) ? `${char}${acc}` : char);
}
char = currentValue;
acc = 0;
}
acc++;
return r;
}, '');
result += char + ((acc > 1) ? acc : '');
return result;
}
const str = 'AVVVBBBVVXDHJFFFFDDDDDDHAAAAJJJDDSLSSSDDDD';
console.info("Compression of string: ", CompressString(str));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment