Compressing string in JavaScript

JavascriptWeb DevelopmentFront End Technology

We are required to write a JavaScript function that takes in a string that might contain some continuous repeating characters.

The function should compress the string like this −

'wwwaabbbb' -> 'w3a2b4'
'kkkkj' -> 'k4j'

And if the length of the compressed string is greater than or equal to the original string we should return the original string.

For example −

'aab' can be compressed to 'a2b1' but it increases its length to 4 so our function should return 'aab'

Example

The code for this will be −

 Live Demo

const str1 = 'wwwaabbbb';
const str2 = 'kkkkj';
const str3 = 'aab';
const compressString = (str = '') => {
   let res = '';
   let count = 1;
   for(let i = 0; i < str.length; i++){
      let cur = str[i];
      let next = str[i + 1];
      if(cur === next){
         count++;
      }else{
         res += cur + String(count);
         count = 1;
      };
   }
   return res.length < str.length ? res : str;
};
console.log(compressString(str1));
console.log(compressString(str2));
console.log(compressString(str3));

Output

And the output in the console will be −

3a2b4
k4j1
aab
raja
Published on 27-Feb-2021 05:38:01
Advertisements