Skip to content

实现 Redux 中的 compose 合并函数。 #6

Open

Description

@CodeRookie262

实现 Redux 中的 compose 合并函数。

compose 函数的作用就是接收多个回调函数并将其整合为一个函数,并且函数由内而外嵌套在一起,内层函数如果返回值则作为实参传递给外层函数;
如

const a = (n) => 6 + n;
const b = (k) => k * 3;
const wrap = compose(a,b); // 等价于 (arg) => b(a(k));
wrap(2); // 24

Activity

  1. CodeRookie262 commented on Dec 23, 2020

    @CodeRookie262
    OwnerAuthor

    实现 Redux 中的 compose 合并函数。

    compose 函数的作用就是接收多个回调函数并将其整合为一个函数,并且函数由内而外嵌套在一起,内层函数如果返回值则作为实参传递给外层函数;
    如

    const a = (n) => 6 + n;
    const b = (k) => k * 3;
    const wrap = compose(a,b); // 等价于 (arg) => b(a(k));
    wrap(2); // 24
    // 解法 1
    function compose(...funs) {
      return funs.reduce(
        (a, b) => arg => b(a(arg)),
        arg => arg
      );
    }
    
    // 解法二
    
    function compose(...funs) {
      return arg => funs.reduce((res, fun) => fun(res), arg);
    }
    
    // 等价于
    function compose(...funs) {
      return arg => {
        let res = arg;
        for (var i = 0, fl = funs.length; i < fl; i++) {
          // 接受返回值,并且将上一个函数的返回值传递给当前函数
          res = funs[i](res);
        }
        return res;
      };
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions