Compress String using Javascript

Compress String using Javascript

I checked for the question internet but didn't find the question to get it.

Compress a given string aacccddd to a2c3d3

Solution

function compressString(vals) {
  let count = 1;
  let checkVal = vals[0];
  let compressedVal = '';

  for (let i = 1; i < vals.length; i++) {
    if (checkVal === vals[i]) {
      count = count + 1;
      continue;
    }

    compressedVal = compressedVal.concat(checkVal, count);
    count = 1;
    checkVal = vals[i];
  }

  compressedVal = compressedVal + checkVal + count;

  return compressedVal.length < vals.length ? compressedVal : vals;
}

const vals = 'aabccccaaAA';
console.log(compressString(vals));

Test Case

  • Only one test case is added and got it working for them.

Output

image.png