Created
April 5, 2017 17:48
-
-
Save irvinemd55/475e07c497f9d4b84d585a37e5350def to your computer and use it in GitHub Desktop.
Compression of a string
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 compressStr(str){ | |
var index = 0; | |
var counter = 1; | |
var starter = str.charAt(0); | |
var newStr = ''; | |
while(index -1 < str.length){ | |
if(starter === str.charAt(index+1)){ | |
counter ++; | |
} else{ | |
newStr += (starter + counter); | |
counter = 1; | |
starter = str.charAt(index+1); | |
} | |
index++; | |
} | |
if (newStr.length < str.length){ | |
return newStr; | |
} else{ | |
return str; | |
} | |
} | |
compressStr('aaabbbccd') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment