我正在尝试使用reduceRight实现具有多个参数的函数组合。这个问题已经在这个link上得到了回答,但使用的输入数据略有不同。由于某种原因,我得到了以下错误:Uncaught TypeError: fn is not a function
。避免使用这种格式的func3 = ([x, y]) => (y > 0 ? x + 3 : x - 3);
。如果有办法解决这个问题,请告诉我。
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执行此操作:
第一种方法
const compose = fns => (...args) =>
fns.reduceRight((acc, fn) => fn(acc), fns.pop()(...args));
第二种方法
const compose = fns => (...args) =>
fns.reduceRight((acc, fn) => fn(...[acc, ...args.slice(1)]), args[0]);
https://stackoverflow.com/questions/56120421
复制相似问题