函数相关
Compose 函数
什么是 compose,比如有以下任务:
let tasks = [step1, step2, step3, step4];
依次执行每个 step 函数,这就是一个 compose
compose 在函数式编程中是一个很重要的工具函数,在这里实现的 compose 有三点说明
- 第一个函数是多元的(接受多个参数),后面的函数都是单元的(接受一个参数)
- 执行顺序是自右向左的
- 所有函数的执行都是同步的
代码类似于下面:
step1(step2(step3(step4(1))));
实现下面代码中的 compose 函数
function fn1(x) {
  return x + 1;
}
function fn2(x) {
  return x + 2;
}
function fn3(x) {
  return x + 3;
}
const a = compose(fn1, fn2, fn3);
a(1);
function compose(...fn) {
  if (!fn.length) return;
  if (fn.length === 1) return fn[0];
  return fn.reduce(
    (pre, cur) =>
      (...args) =>
        pre(cur(...args))
  );
}