关于javascript:JavaScript函数组合

7次阅读

共计 662 个字符,预计需要花费 2 分钟才能阅读完成。

  • 纯函数和柯里化容易引起洋葱代码
  • 函数组合能够让咱们把细粒度的函数重新组合生成一个新的函数
  • 函数组合并没有缩小洋葱代码,只是封装了洋葱代码
  • 函数组合执行程序从右到左
  • 满足结合律既能够把 g 和 h 组合 还能够把 f 和 g 组合,后果都是一样的
const _ = require("lodash");

const reverse = arr => arr.reverse()
const first = arr => arr[0]
const toUpper = s => s.toUpperCase()
  
const lastToupper = _.flowRight(toUpper, first, reverse) 

console.log(lastToupper(['one', 'two', 'three']))
  
// 模仿 lodash 中的 flowRight
function compose (...args) {return function (value) {return args.reverse().reduce(function (acc, fn) {console.log(fn)
      return fn(acc)
    }, value)
  }
}
const composeEs6 = (...args) => value => args.reverse().reduce((acc, fn) => fn(acc), value)
const f = composeEs6(toUpper, first, reverse)
console.log(f(['one', 'two', 'three']))
// 结合律 

原文地址: https://kspf.xyz/archives/71

正文完
 0