Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
CodeRookie262 opened this issue Dec 22, 2020 · 1 comment
Open

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

CodeRookie262 opened this issue Dec 22, 2020 · 1 comment
Labels

Comments

@CodeRookie262
Copy link
Owner

实现 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
@CodeRookie262
Copy link
Owner Author

实现 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
Labels
Projects
None yet
Development

No branches or pull requests

1 participant