使用多个箭头函数组合函数

Composing functions with multiple arrow functions

查看 compose 函数(取自 Redux)

function compose(...funcs) {
    if (funcs.length === 0) {
      return arg => arg
    }

    if (funcs.length === 1) {
      return funcs[0]
    }

    return funcs.reduce((a, b) => (...args) => a(b(...args)))
  }

const double = x => x * 2
const square = x => x * x
const double1 = x => x * 3
compose(double, square, double1)(5)

在最后一个 return 语句中

funcs.reduce((a, b) => (...args) => a(b(...args)))

使用 return 函数的目的是什么 ..args,为什么不直接使用

funcs.reduce((a, b) => a(b(...args))) ?

在您建议的变体中,您将获得 return a(b(...args)) 的结果,而您没有通过 args。所以你会得到一个编译错误 args is not defined.

但在上面的变体中,它 return 是一个函数,它接受参数 (args - 5 作为 args) 传递,return 是 a(b(...args)) 的结果,例如

(...args) => a(b(...args))

看看这个例子。它显示了两种方法的区别。

function a(str) {
  console.log('In a');
  console.log(str);
  return str;
}

function b(str) {
  console.log('In b');
  console.log(str);
  return str;
}

const message = a(b('text')); // This is your variant. Immediate result.
console.log(`Message is ${message}`);

const func = (someText) => a(b(someText)); // This is the given variant. Need to call `func` to get the result.

const anotherMessage = func('anotherText'); Here I need to call `func` and pass my parameter to it.
console.log(`Message is ${anotherMessage}`);