js组合函数的学习

156 阅读1分钟

js组合函数的学习

组合函数是什么?

 某一数据进行函数的调用,执行多个函数,并且依次执行.
 将多个函数组合起来,自动依次调用. 
 这个过程就是对函数的组合,将这个过程称之为 组合函数
function double(n){
  return n * 2
}
function square(m) {
  return m ** 2 // m的2次方
}

var number = 10
var result = square(double(number))
console.log(result);

// 实现最简单的组合函数
function composeFn(fn1, fn2) {
  return function(count) {
    return fn2(fn1(count))
  }
}
var newFn = composeFn(double, square)
console.log(newFn(10));

通用组合函数的实现

function FhCompose(...fns) {
  // 拿到传入的函数个数
  var length = fns.length
  // 对其他类型进行限制
  for( var i = 0; i < length; i++ ) {
    if(typeof fns[i] !== 'function') {
      throw new TypeError('传入类型错误')
    }
  }

  return function(...args) {
    var index = 0
    // 先执行第一次拿到结果
    var result = length ? fns[index].apply(this, args) : args
    // 拿到第一次的结果,执行下一个函数
    while(++index < length) {
      result = fns[index].call(this, result)
    }
    // 返回结果
    return result
  }
}

function double(n) {
  return n * 2
}
function square(m) {
  return m ** 2
}

var fn = FhCompose(double, square)
console.log(fn(1));