【问题标题】:is there a better way to test n functions with reduce? [JS]有没有更好的方法来测试和减少功能? [JS]
【发布时间】:2020-05-01 17:39:18
【问题描述】:

我创建了一个简单的函数来测试(调用)“n”个参数(函数)并将结果作为数组返回,但我不确定这是否是使用 reduce 的正确方法(检查下面的注释行) .

const sucess = () => true;
const failed = () => false;


const tester = (...args) => {
 return [...args].reduce((acc,currentValue) => { 
    if(typeof acc === 'function') // this is right?
        return [acc(),currentValue()]
    return [...acc,currentValue()]
  });
}

console.log(tester(sucess,failed,failed,sucess));

你在做什么

【问题讨论】:

  • 我认为你应该使用map 而不是reduce
  • 永远不要在没有第二个参数的情况下使用reduce,即初始累加器值。

标签: javascript function testing ecmascript-6 reduce


【解决方案1】:

您似乎正在尝试考虑第一次迭代,acc 将成为数组的第一个元素。

幸运的是reduce 已经有办法解决这个问题。根据MDN,最后一个参数是initialValueacc 将以它开头。只有当没有给出initialValue 时,acc 才会成为函数。在您的情况下,您可以像这样传入一个空数组[]

const sucess = () => true;
const failed = () => false;


const tester = (...args) => {
  return [...args].reduce((acc,currentValue) => ([...acc,currentValue()]), []);
}

console.log(tester(sucess,failed,failed,sucess));

这使得逻辑非常简单,因为您可以保证 acc 始终是一个数组,而不是其他任何东西。

顺便说一句,正如 cmets 中所指出的,您正在做的是将带有映射的一些值的数组转换为其他值的数组。这是Array.map() 的确切用例。上面可以更简洁地完成如下:

const sucess = () => true;
const failed = () => false;


const tester = (...args) => args.map(fn => fn());

console.log(tester(sucess,failed,failed,sucess));

【讨论】:

  • "这使得逻辑非常简单,因为您可以保证 acc 始终是一个数组,而不是其他任何东西。"就这样。很好的答案,抱歉回复晚了。你能看到编辑吗?谢谢!
  • @elaineee 我看不到编辑中的代码与原始问题之间有任何关系。我建议发布一个新问题,如果您认为这个问题提供了相关的上下文,请在发布新问题时插入一个指向它的链接。
猜你喜欢
  • 1970-01-01
  • 2014-08-31
  • 1970-01-01
  • 2015-09-10
  • 1970-01-01
  • 2019-08-26
  • 2013-08-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多