首页 > 解决方案 > 将两个回调函数合二为一

问题描述

这是问题...

“在标记为“在此处添加代码”的地方将代码添加到函数eitherCallback以实现所需的控制台日志。使用eitherCallback将两个回调合并为一个回调,然后将该回调传递给filterArray的结果应与只需将两个回调传递给上一个挑战中的任一过滤器。”

这是我知道可行的先前挑战的解决方案...

function eitherFilter(array, callback1, callback2) {
  // ADD CODE HERE
  const newArr = [];
  for (let i = 0; i < array.length; i++) {
    if (callback1(array[i]) || callback2(array[i])) {
      newArr.push(array[i]);
    }
  }
  return newArr;
}

// Uncomment these to check your work!
 const arrOfNums = [10, 35, 105, 9];
 const integerSquareRoot = n => Math.sqrt(n) % 1 === 0;
 const over100 = n => n > 100;
 console.log(eitherFilter(arrofNums, integerSquareRoot, over100)); // should log: [105, 9]

这是给出的代码...

function eitherCallback(callback1, callback2) {
  // ADD CODE HERE
}

// Uncomment these to check your work!
 function filterArray(array, callback) {
   const newArray = [];
   for (let i = 0; i < array.length; i += 1) {
     if (callback(array[i], i, array)) newArray.push(array[i]);
   }
   return newArray;
 }
 const arrOfNums = [10, 35, 105, 9];
 const integerSquareRoot = n => Math.sqrt(n) % 1 === 0;
 const over100 = n => n > 100;
 const intSqRtOrOver100 = eitherCallback(integerSquareRoot, over100);
 console.log(filterArray(arrOfNums, intSqRtOver100)); // should log: [105, 9]

我对该怎么做感到困惑。谁能给我一些提示?我什至不知道如何开始回答它!

提前致谢...

标签: javascriptfiltercallback

解决方案


您不需要太多 - 您只需要创建eitherCallback一个高阶函数,该函数将两个回调作为初始参数,并执行并返回您在此处执行的逻辑:

callback1(array[i]) || callback2(array[i])

喜欢:

const eitherCallback = (callback1, callback2) => x => callback1(x) || callback2(x);

// Uncomment these to check your work!
 function filterArray(array, callback) {
   const newArray = [];
   for (let i = 0; i < array.length; i += 1) {
     if (callback(array[i], i, array)) newArray.push(array[i]);
   }
   return newArray;
 }
 const arrOfNums = [10, 35, 105, 9];
 const integerSquareRoot = n => Math.sqrt(n) % 1 === 0;
 const over100 = n => n > 100;
 const intSqRtOrOver100 = eitherCallback(integerSquareRoot, over100);
 console.log(filterArray(arrOfNums, intSqRtOrOver100)); // should log: [105, 9]


推荐阅读