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) #14

Open
jinjiaxing opened this issue Apr 1, 2019 · 0 comments
Open

Redux源码分析(Compose) #14

jinjiaxing opened this issue Apr 1, 2019 · 0 comments

Comments

@jinjiaxing
Copy link
Owner

Redux源码分析(Compose)

Composes functions from right to left.

这个我们就直接举例子去说明一下会让大家更容易去理解compose方法

组合函数,将函数串联起来执行。就像domino一样,推倒第一个函数,其他函数也跟着执行。
首先我们看一个简单的例子。

// 实现公式: f(x) = (x + 100) * 2 - 100
const add = a => a + 100;
const multiple = m => m * 2;
const subtract = s => s - 100;

// 深度嵌套函数模式 deeply nested function,将所有函数串联执行起来。
subtract(multiple(add(200)));

上述例子执行结果为:500

compose 其实是通过reduce()方法,实现将所有函数的串联。不直接使用深度嵌套函数模式,增强了代码可读性。不要把它想的很难。

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)))
}

compose(subtract, multiple, add)(200);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant