Skip to content

Instantly share code, notes, and snippets.

@irvinemd55
Created April 5, 2017 17:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save irvinemd55/475e07c497f9d4b84d585a37e5350def to your computer and use it in GitHub Desktop.
Save irvinemd55/475e07c497f9d4b84d585a37e5350def to your computer and use it in GitHub Desktop.
Compression of a string
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