Skip to content

Instantly share code, notes, and snippets.

@senthil1216
Last active August 29, 2015 14:13
Show Gist options
  • Save senthil1216/0c4c9ce3d6e117fcc5d7 to your computer and use it in GitHub Desktop.
Save senthil1216/0c4c9ce3d6e117fcc5d7 to your computer and use it in GitHub Desktop.
Compress String using Javascript
function compressStringPatterns(inputStr)
{
var inp = inputStr.trim().split(''), // convert string to an array
prev='',
count='',
out='';
for(var i = 0; i < inp.length; i++){
// if the prev character is same as the current then incr. the counter
if(prev === inp[i]){
count = count + 1;
}
else{
// .. else append the count of the char and the char
out = out + count + '' + prev;
prev = inp[i]; // .. reset the prev to the current one
count = 1; // .. initialize the counter
}
}
//this is for appending the last count of the character and the character
out = out + count + '' + prev;
return out;
}
console.log( compressStringPatterns( '111223332' )); //==> 31223312
console.log( compressStringPatterns( '1' )); //==> 11
console.log( compressStringPatterns( '12' )); //==> 1112
console.log( compressStringPatterns( ' ' )); //==> ''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment