如何在es6 / javascript中阅读功能组合?
背景
组合将两个函数合在一起,形成第三个函数,功能是另一个的输入。
Composition is putting two functions together to form a third function where the output of one function is the input of the other.
无论我看多少,我都在努力阅读它。特别是为什么 compose()
return => (a)=>
捕获本地范围内的 121.2121212
。另外我也努力争取最终的fn f(g(a))
将会看到所有的值/ fn存在使用变量。
No matter how much I look at this I struggle with how to read it. In particular why the compose()
return => (a) =>
captures the 121.2121212
in local scope. Also I struggle with how final fn f(g(a))
would look with all the values/fn present w/o the use of variables.
问题:有没有人有任何技术或图表来快速阅读这样的示例;我如何进行智能调试并按照功能流程?
Question: Does anyone have any techniques or diagrams for quickly reading examples like this; how can I mentally debug and follow the function flow?
const compose = (f, g) => (a) => f(g(a)) // Definition
const floorAndToString = compose((val) => val.toString(), Math.floor) // Usage
floorAndToString(121.212121) // '121'
如TJ所述Crowder,它经常帮助重写箭头功能作为常规功能。所以函数:
As mentioned by T.J. Crowder, it often helps rewriting arrow functions as regular functions. So the function:
const compose = (f, g) => (a) => f(g(a))
可以重写为:
function compose (f, g) {
return function (a) {
return f(g(a));
}
}
现在可能更明显的是发生了什么。所以现在让我们重写其他部分:
Now it is perhaps more obvious what's going on. So now let's rewrite the other parts:
const floorAndToString = compose((val) => val.toString(), Math.floor)
可以重写为:
function convertToString (val) { return val.toString() };
const floorAndToString = compose(convertToString, Math.floor);
现在可能更明显的是,撰写
函数将返回函数:
Now it may be more obvious that the compose
function will return the function:
// remember that we pass `convertToString` as `f`
// and `Math.floor` as `g`:
function (a) {
return convertToString(Math.floor(a));
}
所以很明显,函数 floorAndToString
只返回 convertToString(Math.floor(a))
的结果。没有什么特别的 compose
,它捕获 121.2121212
,因为它没有。而是创建一个函数,其中 121.2121212
可以作为参数传递给 convertToString(Math.floor(a))
。
So it's obvious that the function floorAndToString
simply returns the result of convertToString(Math.floor(a))
. There is nothing special about compose
that captures 121.2121212
because it doesn't. Instead it creates a function where 121.2121212
can be passed as an argument to convertToString(Math.floor(a))
.