函数组合

193 阅读1分钟

  • 纯函数和柯里化很容易写出洋葱代码:h(g(f(x)))
    获取数组的最后一个元素再转换成大写字母:_.toUpper(_.first(_.reverse(array)))
  • 函数的组合,可以让我们把细粒度的函数组合生成一个新的函数
    fn = compose(f1,f2,f3) b = fn
  • 函数组合概念:
    如果一个函数要经过多个函数处理才能得到最终值,这时候可以把中间过程的函数合并成一个函数
    函数就像数据的管道,函数组合就是把这些管道连起来,让数据穿过多个管道形成最终的结果
    函数组合默认从右到左执行
  1. 函数组合的演示:
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]))
  1. lodash中的函数组合
// lodash 中的函数组合的方法 _.flowRight()
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']))
  1. 组合函数原理模拟
// 模拟 lodash 中的 flowRight

const reverse = arr => arr.reverse()
const first = arr => arr[0]
const toUpper = s => s.toUpperCase()

// function compose (...args) {
//   return function (value) {
//     return args.reverse().reduce(function (acc, fn) {
//       return fn(acc)
//     }, value)
//   }
// }

const compose = (...args) => value => args.reverse().reduce((acc, fn) => fn(acc), value)

const f = compose(toUpper, first, reverse)
console.log(f(['one', 'two', 'three']))
  1. 函数组合结合律 函数组合要满足结合律: 既可以把g和h组合,也可以把f和g组合,结果是一样的
const _ = require('lodash')

// const f = _.flowRight(_.toUpper, _.first, _.reverse)
// const f = _.flowRight(_.flowRight(_.toUpper, _.first), _.reverse)
const f = _.flowRight(_.toUpper, _.flowRight(_.first, _.reverse))
console.log(f(['one', 'two', 'three']))
  1. 函数组合的调试
// NEVER SAY DIE  --> never-say-die

const _ = require('lodash')

// const log = v => {
//   console.log(v)
//   return v
// }

const trace = _.curry((tag, v) => {
  console.log(tag, v)
  return v
})

// _.split()
const split = _.curry((sep, str) => _.split(str, sep))

// _.toLower()
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'))