背景:
Composition is putting two functions together to form a third function where the output of one function is the input of the other.
无论我看了多少次,我都很难阅读它。特别是为什么 compose()
返回 => (a) =>
在本地范围内捕获 121.2121212
。另外,我还很困惑最终的 fn f(g(a))
在所有值/fn 不使用变量的情况下看起来如何。
问题:有谁有快速阅读这样的示例的技术或图表吗?我如何在心里调试并遵循功能流程?
const compose = (f, g) => (a) => f(g(a)) // Definition
const floorAndToString = compose((val) => val.toString(), Math.floor) // Usage
floorAndToString(121.212121) // '121'
最佳答案
正如 T.J. 所提到的Crowder,它通常有助于将箭头函数重写为常规函数。所以函数:
const compose = (f, g) => (a) => f(g(a))
可以重写为:
function compose (f, g) {
return function (a) {
return f(g(a));
}
}
现在发生的事情也许更加明显了。现在让我们重写其他部分:
const floorAndToString = compose((val) => val.toString(), Math.floor)
可以重写为:
function convertToString (val) { return val.toString() };
const floorAndToString = compose(convertToString, Math.floor);
现在可能更明显的是,compose
函数将返回该函数:
// remember that we pass `convertToString` as `f`
// and `Math.floor` as `g`:
function (a) {
return convertToString(Math.floor(a));
}
很明显,函数floorAndToString
只是返回convertToString(Math.floor(a))
的结果。捕获 121.2121212
的 compose
没有什么特别之处,因为它没有捕获。相反,它创建了一个函数,其中 121.2121212
可以作为参数传递给 convertToString(Math.floor(a))
。
关于javascript - 如何阅读 es6/javascript 中的函数组合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41823053/