Reputation: 815
I have the following compress/decompress algorithm. I need to use javascript Array reduce
. Not really sure how to apply it here. Could someone please show me how.
Code
function StringCompression(str){
let compString = '';
let i;
for(i = 0; i < str.length; i++){
let currentLetter = str[i];
let curCount = 1;
while(str[i+1] === currentLetter){
curCount++;
i++;
}
compString += currentLetter + curCount;
}
if(compString.length > str.length){
return str;
}
return "\nCompressing string '" + str + "'... " + compString;
}
function StringDecompression(compString){
let DecompString = '';
let i;
for(i = 0; i < compString.length; i++){
let currentLetter = compString[i];
let currentInt = parseInt(compString[i+1]);
if(currentInt > 0){
let j;
for(j = 0; j < currentInt; j++){
DecompString += currentLetter;
}
}
}
return "Decompressing string '" + compString + "'... " + DecompString + "\n";
}
console.log(StringCompression("aabbbcccccaa"));//output >> a2b3c5a2
console.log(StringDecompression("a2b3c5a2x4"));//output >> aabbbcccccaaxxxx
Upvotes: 1
Views: 1379
Reputation: 83
I actually love using reduce()
. But as others pointed out, reduce is a method on an Array. So you need to convert your string to an array first. It can be improved, but thought I'd keep it simple and easy to read for you to compare.
I converted your algorithm with the same logic. It may be flawed logic dependent on what the use case is, but none the less, it works like yours.
function StringCompressReduce(str) {
let string = str.split(""),
counter = 1,
compString = string.reduce(function (
accumulator,
currentValue,
currentIndex,
array
) {
if (currentValue === array[currentIndex + 1]) {
//increment and move on
counter++;
return accumulator;
} else {
//save letter and number
accumulator += (currentValue + counter);
counter = 1;
return accumulator;
}
}, "");
return "\nCompressing string '" + str + "'... " + compString;
}
function StringDecompressReduce(str) {
let string = str.split(""),
DecompString = string.reduce(function (
accumulator,
currentValue,
currentIndex,
array
) {
let parseValue = parseInt(currentValue);
if (!isNaN(parseValue)) {
// Save prev char x times
accumulator += Array(parseValue + 1).join(array[currentIndex - 1]);
}
return accumulator;
}, "");
return "Decompressing string '" + str + "'... " + DecompString + "\n";
}
console.log(StringCompressReduce("aabbbcccccaa"));
console.log(StringDecompressReduce("a2b3c5a2x4"));
Upvotes: 2