函数合成(function composition)指的是将多个函数合成为一个函数。
在 JS 函数式编程中,你可以经常看到如下表达式运算。
a(b(c(x)))
这看起来很不雅观,为了解决函数多层调用的嵌套问题,我们需要用到函数合成。其语法格式如下:
const f = compose(a, b, c) // 合成函数 f(x)
我们使用前天写的
如何在 JavaScript 中使用管道(管道运算符)?
中的示例:
const compose = f => g => x => f(g(x))
const title = 'Front End Interview'
const toLowerCase = (str) => str.toLowerCase()
const addHyphens = (str) => str.replace(/\s/g, '-')
compose(toLowerCase)(addHyphens)(title) // "front-end-interview"
正如你所看到的,
compose
函数的作用就是将两个函数合成为一个。
compose
将两个函数串联起来执行,
toLowerCase
函数返回的结果会传递给下一个函数
addHyphens
中作为参数。
更加详细的例子可以查看
JavaScript专题之函数组合
。