Javascript压缩/解压缩。如何使用Array reduce

时间:2018-01-30 10:00:00

标签: javascript

我有以下压缩/解压缩算法。我需要使用javascript数组reduce。不确定如何在这里应用它。有人可以告诉我如何。

代码

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

1 个答案:

答案 0 :(得分:2)

我真的喜欢使用reduce()。但正如其他人所指出的,reduce是Array上的一种方法。所以你需要先将字符串转换为数组。它可以改进,但我认为我保持简单易读,便于您比较。

我用相同的逻辑转换了你的算法。它可能是有缺陷的逻辑,取决于用例是什么,但同样,它就像你的一样。

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"));