组合函数

个人粗鄙理解组合函数:

  组合意味着多个函数,类似一种嵌套关系,比如2个函数组合,第二个函数是以第一个函数的结果作为参数的函数。

  多个函数组合也类似,第n个函数的参数是以第n-1 函数的结果作为参数

下面以两个函数为例子

const add = (a, b) => a + b // 求和
const square = a => a * a // 平方

1. 直观的组合函数

const fn = (x, y) => square(add(x, y)) 
console.log(fn(1, 2)) // 输出结果 9

 

2. 封装组合函数

const compose = (fn1, fn2) => (...arg) => fn2(fn1(...arg))
const fn = compose(add ,square)
console.log(fn(1, 2)) // 输出结果 9

这种方式值合适2个组合函数

3.2个以上的组合函数

const compose = (...[first, ...other]) => (...arg) => {
  let ret = first(...arg) // 第一个函数 执行得到结果ret
  // 执行其他函数,把结果保存至ret 作为下一个函数的参数

 other.forEach(fn => {
     ret = fn(ret)
  })
  // 返回最终的执行结果
  return ret
}
const fn = compose(add ,square, square, square, square)
console.log(fn(1, 2)) // 输出结果 43046721
原文地址:https://www.cnblogs.com/yflbk-2016/p/13150939.html