使用reduceRight()的多参数可组合函数实现

时间:2019-04-25 06:23:11

标签: javascript

我正在尝试使用reduceRight重新实现功能组合。这是我要重新实现的功能组合:

const compose = function([func1, func2, func3]) {
  return function(value1, value2) {
    return func1(func2(func3(value1, value2)));
  };
};

const func3 = (x, y) => {
  return y > 0 ? x + 3 : x - 3;
};

const func2 = x => {
  return x ** 2;
};

const func1 = x => {
  return x - 8;
};

const fn = compose([func1, func2, func3]);

console.log(fn('3', 1)); // 1081
console.log(fn('3', -1)); // -8

以下代码是上述功能的重新实现。看来参数y越来越undefined,我不确定为什么。

const compose = (...args) => value =>
  args.reduceRight((acc, fn) => fn(acc), value);

const func3 = (x, y) => {
  return y > 0 ? x + 3 : x - 3;
};

const func2 = x => {
  return x ** 2;
};

const func1 = x => {
  return x - 8;
};

const fnOne = compose(
  func1,
  func2,
  func3
)('3', 1);
console.log(fnOne);//-8

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

1 个答案:

答案 0 :(得分:1)

类似于compose,您可以使用rest parameter语法获取values的数组。然后destructurefunc3参数来获得xy,如下所示:

const compose = (...args) => (...values) =>
  args.reduceRight((acc, fn) => fn(acc), values);

// an array of values is passed here
// destructure to get the x and y values
const func3 = ([x, y]) => y > 0 ? x + 3 : x - 3;

const func2 = x => x ** 2;

const func1 = x =>  x - 8;

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

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