zor*_*rza 6 javascript functional-programming ecmascript-6
如何将此函数组合转换为更易读的格式?
funcA(argumentA, funcB(argumentA, funcC(argumentA, argumentB)))
Run Code Online (Sandbox Code Playgroud)
我想要实现的是更像这样的东西:
compose(funcC, funcB, funcA)(argumentA, argumentB)
Run Code Online (Sandbox Code Playgroud)
我正在使用这个 compose 函数实现:
const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args)))
Run Code Online (Sandbox Code Playgroud)
问题是我在所有函数调用中都需要参数 A 作为第一个参数,每个函数返回一个值作为第二个参数传递给下一个函数。我知道我可以创建单独的函数返回函数并像这样使用它们:
compose(funcCWithArg(argumentA), funcBWithArg(argumentA), funcAWithArg(argumentA))(argumentB)
Run Code Online (Sandbox Code Playgroud)
但在我的实际情况中,不仅有三个,而且还有更多,这需要大量的代码才能将它们写下来。有没有更简单的方法来做到这一点?
编辑:我不能使用任何外部库。只有香草js。
首先创建新函数,这些函数是使用的部分应用程序bind。然后使用compose您已有的功能:
const funcA = (x, y) => `A(${x}, ${y})`;
const funcB = (x, y) => `B(${x}, ${y})`;
const funcC = (x, y) => `C(${x}, ${y})`;
const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args)));
const partials = (...fns) => (...args) => fns.map((f) => f.bind(this, ...args));
console.log(compose(...partials(funcA, funcB, funcC)("a"))("b"));
// Output:
// A(a, B(a, C(a, b)))
Run Code Online (Sandbox Code Playgroud)
更新
您还可以构建一个函数,该函数使用传递的第一个参数组合部分函数,然后使用其他参数调用它们。(我想这就是你想要的?我不是 100% 确定如何处理两个以上的参数。)
const partialCompose = (...fns) => (...args) => compose(...partials(...fns)(args[0]))(...args.slice(1));
console.log(partialCompose(funcA, funcB, funcC)("a", "b")); // same output as above
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1642 次 |
| 最近记录: |