javascript - 如何阅读 es6/javascript 中的函数组合?

标签 javascript functional-programming ecmascript-6 composition

背景:

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 不使用变量的情况下看起来如何。

问题:有谁有快速阅读这样的示例的技术或图表吗?我如何在心里调试并遵循功能流程?

Reference:

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.2121212compose 没有什么特别之处,因为它没有捕获。相反,它创建了一个函数,其中 121.2121212 可以作为参数传递给 convertToString(Math.floor(a))

关于javascript - 如何阅读 es6/javascript 中的函数组合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41823053/

相关文章:

javascript - 带有分配函数返回值的变量的 javascript 模式的名称是什么?

javascript - 如何在javascript中每次点击时在数组内创建子对象

javascript - 在 React Js 中处理多个上传图像 + 将其发送到服务器

javascript - ES6 导入和导出是如何工作的?

javascript - IONIC2 - ionic 服务时出现语法错误

javascript - 使用 Q.allSettled 时 Q.fail 不起作用

javascript - sap.m.树实现

Javascript更改空白选项标签的文本

clojure - 基于 Clojure 类型的比较

functional-programming - 需要帮助理解这个 erlang 代码