Created
October 3, 2017 20:54
-
-
Save unilecs/93810f5924a67607c7fa8906759297d6 to your computer and use it in GitHub Desktop.
Compress string: ABBCCCD -> AB2C3D
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
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