Javascript压缩/解压缩。如何使用数组reduce
我有下面的压缩/解压缩算法。我需要使用javascript数组Javascript压缩/解压缩。如何使用数组reduce,javascript,Javascript,我有下面的压缩/解压缩算法。我需要使用javascript数组reduce。我不知道如何在这里应用它。有人能告诉我怎么做吗 代码 function StringCompression(str){ let compString = ''; let i; for(i = 0; i < str.length; i++){ let currentLetter = str[i]; let curCount = 1;
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
函数字符串压缩(str){
让compString='';
让我;
对于(i=0;istr.length){
返回str;
}
返回“\n压缩字符串”'+str+“'…”+compString;
}
函数字符串解压缩(compString){
让字符串=“”;
让我;
对于(i=0;i0){
让j;
对于(j=0;j>a2b3c5a2
日志(字符串解压缩(“a2b3c5a2x4”)//输出>>aabbbcccacaxxxx
我实际上喜欢使用reduce()
。但正如其他人指出的,reduce是一种数组方法。因此,首先需要将字符串转换为数组。它是可以改进的,但我想我会保持它的简单易读,以便你们进行比较
我用同样的逻辑转换了你的算法。它的逻辑可能有缺陷,这取决于用例是什么,但尽管如此,它的工作原理与您的一样
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"));
“我需要使用javascript数组
reduce
”-为什么?您的代码似乎工作正常。它根本不使用数组。我从中获得了引用的链接,但我首先尝试了自己的方法StringCompression=str=>(str.match(/()\1*/g)| |[]).map(x=>x[0]+x.length)。连接(“”)代码>和StringDecompression=str=>str.replace(/()(\d)/g,(x,l)=>x.repeat(l))代码>-对不起,reduce
没有使用案例“我被提供了此链接以供参考”-由谁提供?为什么?