- 纯函数和柯里化很容易写出洋葱代码:h(g(f(x)))
获取数组的最后一个元素再转换成大写字母:_.toUpper(_.first(_.reverse(array)))
- 函数的组合,可以让我们把细粒度的函数组合生成一个新的函数
fn = compose(f1,f2,f3)
b = fn
- 函数组合概念:
如果一个函数要经过多个函数处理才能得到最终值,这时候可以把中间过程的函数合并成一个函数
函数就像数据的管道,函数组合就是把这些管道连起来,让数据穿过多个管道形成最终的结果
函数组合默认从右到左执行
- 函数组合的演示:
function compose (f, g) {
return function (value) {
return f(g(value))
}
}
function reverse (array) {
return array.reverse()
}
function first (array) {
return array[0]
}
const last = compose(first, reverse)
console.log(last([1, 2, 3, 4]))
- lodash中的函数组合
const _ = require('lodash')
const reverse = arr => arr.reverse()
const first = arr => arr[0]
const toUpper = s => s.toUpperCase()
const f = _.flowRight(toUpper, first, reverse)
console.log(f(['one', 'two', 'three']))
- 组合函数原理模拟
const reverse = arr => arr.reverse()
const first = arr => arr[0]
const toUpper = s => s.toUpperCase()
const compose = (...args) => value => args.reverse().reduce((acc, fn) => fn(acc), value)
const f = compose(toUpper, first, reverse)
console.log(f(['one', 'two', 'three']))
- 函数组合结合律
函数组合要满足结合律:
既可以把g和h组合,也可以把f和g组合,结果是一样的
const _ = require('lodash')
const f = _.flowRight(_.toUpper, _.flowRight(_.first, _.reverse))
console.log(f(['one', 'two', 'three']))
- 函数组合的调试
const _ = require('lodash')
const trace = _.curry((tag, v) => {
console.log(tag, v)
return v
})
const split = _.curry((sep, str) => _.split(str, sep))
const join = _.curry((sep, array) => _.join(array, sep))
const map = _.curry((fn, array) => _.map(array, fn))
const f = _.flowRight(join('-'), trace('map 之后'), map(_.toLower), trace('split 之后'), split(' '))
console.log(f('NEVER SAY DIE'))