本文共 2601 字,大约阅读时间需要 8 分钟。
Function composition is the pointwise application of one function to the result of another. Developers do it in a manual manner every day when the nest functions:
函数组成是将一个函数逐点应用到另一个函数的结果。 当Nest运行时,开发人员每天都会以手动方式进行操作:
compose = (fn1, fn2) => value => fn2(fn1(value))
But this is hard to read. There is a better way using function composition. Instead of reading them from inside out:
但这很难读。 使用功能组合有更好的方法。 而不是从内到外阅读它们:
add2AndSquare = (n) => square(add2(n))
We can use a higher order function to chain them in an ordered way.
我们可以使用一个更高阶的函数将它们有序地链接起来。
add2AndSquare = compose( add2, square)
A simple implementation of compose would be:
compose的一个简单实现是:
compose = (f1, f2) => value => f2( f1(value) );
To get even more flexibility we can use the reduceRight function:
为了获得更大的灵活性,我们可以使用reduceRight函数:
compose = (...fns) => (initialVal) => fns.reduceRight((val, fn) => fn(val), initialVal);
Reading compose from left to right allows a clear chaining of higher order functions. Real world examples are adding authentications, logging and context properties. It’s a technique that enables reusability on the highest level. Here are some examples how to use it:
从左到右读取compose可以清楚地链接高阶函数。 现实世界中的示例包括添加身份验证,日志记录和上下文属性。 这是一种在最高级别上实现可重用性的技术。 以下是一些如何使用它的示例:
// exampleconst add2 = (n) => n + 2;const times2 = (n) => n * 2;const times2add2 = compose(add2, times2);const add6 = compose(add2, add2, add2);times2add2(2); // 6add2tiems2(2); // 8add6(2); // 8
You might think this is advanced functional programming and it’s not relevant for frontend programming. But it’s also useful in Single Page Applications. For example you can add behavior to a React component by using higher order components:
您可能会认为这是高级功能编程,与前端编程无关。 但是在单页应用程序中它也很有用。 例如,您可以使用高阶组件将行为添加到React组件:
function logProps(InputComponent) { InputComponent.prototype.componentWillReceiveProps = function(nextProps) { console.log('Current props: ', this.props); console.log('Next props: ', nextProps); }; return InputComponent;}// EnhancedComponent will log whenever props are receivedconst EnhancedComponent = logProps(InputComponent);
In conclusion function composition enables reusability of functionality at a very high level. If the functions are structured well it enables developers to created new behavior based upon existing behavior.
总之,功能组合可以在很高的层次上实现功能的可重用性。 如果功能结构合理,则开发人员可以根据现有行为创建新行为。
It also increases readability of implementations. Instead of nesting functions you can clearly chain functions and create higher order functions with meaningful names.
它还增加了实现的可读性。 除了嵌套函数,您还可以清楚地链接函数并使用有意义的名称创建高阶函数。
翻译自:
转载地址:http://fxzzd.baihongyu.com/