I have two inputs (original and comprimida). The original one is like this one "bbbddef" which in a compressed form would be "b3d2e1f1" (Three times b, two times d, one for e and one for f). However, when I have a original like this one: "aaaaaaaaaaabcdda" that should be "a11b1c1d2a1" it only counts till 9 because the for cannot go above 9 (two digits). How can I solve this? Thanks in advance.
Here's the code
var original = "aaaaaaaaaaabcdda";
var comprimida = "a11b1c1d2a1";
var res = "";
for(var i = 0; i < comprimida.length; i+=2){
let letra = comprimida.charAt(i);
let numero = comprimida.charAt(i+1);
for(let j=0; j<numero; j++){
res += letra;
}
}
if(original == res){
alert("SI");
} else {
alert("NO");
}
The code should do 'a' 11 times and it's not doing so since it only takes the first 1 from 11. But I can't make it count two digits only because then every other solution for 'a' being less than 10 would be wrong.
This solution reads char by char. If it's a letter it is being remembered, if it's a digit it's being calculated to be a number. Then, if it's a letter again we repeat number of times the last remembered letter.
var comprimida = "a11b1c1d2a1";
var result = "";
var current = "";
var number = 0;
comprimida.split("").forEach(function(char) {
if (char >= 'a' && char <= 'z') {
result += current.repeat(number)
number = 0;
current = char;
} else {
number = number * 10 + +char
}
})
result += current.repeat(number)
console.log(result)