Uncompress a String, repeat chars `n` times

I have the following problem statement:

Write a function, uncompress, that takes in a string as an argument. The input string will be formatted into multiple groups according to the following pattern:

number + char

for example, '2c' or '3a'.

The function should return an uncompressed version of the string where each 'char' of a group is repeated 'number' times consecutively. You may assume that the input string is well-formed according to the previously mentioned pattern.

test_00: uncompress("2c3a1t"); // -> 'ccaaat'

Here is my code which is using a stack. The problem is that it's only returning 'cc' and I can't figure out why. I've console logged what goes into the IF ELSE and I'm hitting both so I don't understand why nothing gets pushed to the stack.

Would really appreciate the help if someone can spot what I'm missing.

const uncompress = (s) => { 
  const nums = '23456789';
  const stack = []; 
  for (let char of s) {
    if (nums.includes(char)) {
      stack.push(Number(char));
    } else {
      const num = stack.pop();
      stack.push(char.repeat(num));
    };
  };
  return stack.join('');
};

console.log(uncompress("2c3a1t")); // -> 'ccaaat'

Solution 1:

Here's how I would do it:

Split the string up into pairs of numbers and chars:

str.match(/\d+[a-zA-Z]/g)

And reduce that array to a string, while taking each value from the array, getting the char from it (cv.match(/[a-zA-Z]/)[0]) and repeating it according to the number (.repeat(parseInt(cv)))

const uncompress = str => str.match(/\d+[a-zA-Z]/g).reduce((acc, cv) =>
  acc + cv.match(/[a-zA-Z]/)[0].repeat(parseInt(cv)), "")

console.log(uncompress("2c3a1t"))
console.log(uncompress("27b1d8g"))