I wanted to write a function that takes a compressed string and outs the decompressed string.
A compressed string like a2b2c3 and the decompress string is aabbccc More examples would be
`a` -> `a`
`ab12` -> `abbbbbbbbbbbb`
`a3b2a2` -> `aaabbaa
I tried to implement it but it is really messy and buggy for compressed strings like ab12
function isNumeric(num) {
if (num === '') return false
if (num === null) return false
return !isNaN(num)
}
function decompress(compressedStr) {
const array = compressedStr.split('')
let prevChar, str = ''
for(let i = 0; i < array.length; i++) {
if(i === 0) {prevChar = array[i]}
if(isNumeric(array[i])) {
str += prevChar.repeat(Number(array[i]))
prevChar = null
} else {
if(!prevChar) prevChar = array[i]
else {
str += prevChar
prevChar = array[i]
}
}
}
return str
}
Now it works for a3b2a2 but it is buggy for cases like ab12 . Need help to rewrite this function to make it work.
from JavaScript algo: decompress a compressed string
No comments:
Post a Comment