首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用reduceRight() - JavaScript组合具有多个参数的函数

使用reduceRight() - JavaScript组合具有多个参数的函数
EN

Stack Overflow用户
提问于 2019-05-14 06:03:00
回答 3查看 589关注 0票数 1

我正在尝试使用reduceRight实现具有多个参数的函数组合。这个问题已经在这个link上得到了回答,但使用的输入数据略有不同。由于某种原因,我得到了以下错误:Uncaught TypeError: fn is not a function。避免使用这种格式的func3 = ([x, y]) => (y > 0 ? x + 3 : x - 3);。如果有办法解决这个问题,请告诉我。

代码语言:javascript
复制
 const compose = (...fns) => (...args) =>
      fns.reduceRight((acc, fn) => fn(acc), args);

    const func3 = (x, y) => (y > 0 ? x + 3 : x - 3);
  //const func3 = ([x, y]) => (y > 0 ? x + 3 : x - 3); - avoid using this version

    const func2 = x => x ** 2;

    const func1 = x => x - 8;

    const fnOne = compose([func1, func2, func3])('3', 1);
    console.log(fnOne); // should be 1081

    const fnTwo = compose([func1, func2, func3])('3', -1);
    console.log(fnTwo); //should be -8


  [1]: https://stackoverflow.com/questions/55842990/multiple-arguments-composible-function-implementation-using-reduceright

解决方案

Array#reduceRight只支持一个currentValue,所以我们不能让一个函数接受多个参数。唯一的方法是避免在第一次调用时使用reduceRight,方法是从数组中弹出它,并将其称为手动调用,而不是让reduceRight执行此操作:

第一种方法

代码语言:javascript
复制
const compose = fns => (...args) =>
      fns.reduceRight((acc, fn) => fn(acc), fns.pop()(...args));

第二种方法

代码语言:javascript
复制
const compose = fns => (...args) =>
      fns.reduceRight((acc, fn) => fn(...[acc, ...args.slice(1)]), args[0]);
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56120421

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档