柯里化与偏函数

131 阅读1分钟

柯里化与偏函数

柯里化

  • 将一个多参数函数转换成多个单参数函数,也就是将一个 n 元函数转换成 n 个一元函数

  • 不会调用函数,只对函数进行转换

  • 柯里化可以看做偏函数的一种特殊的应用

const myCurrying = function (fn) {
  return function _curry(...args) {
    if (args.length < fn.length) {
      return function () {
        return _curry.apply(this, [...args, ...arguments])
      }
    } else {
      return fn.apply(this, args)
    }
  }
}

偏函数

  • 固定一个函数的一个或者多个参数,也就是将一个 n 元函数转换成一个 n - x 元函数

  • 不会调用函数,只对函数进行转换

const _ = {}
const partial = function (fn) {
  const args = [...arguments].slice(1)
  return function (...newArgs) {
    let position = 0
    for (let i = 0; i < args.length; i++) {
      args[i] = args[i] === _ ? newArgs[position++] : args[i]
    }
    while (position < newArgs.length) {
      args.push(newArgs[position++])
    }
    if(args.length < fn.length>){
      throw new Error('Insufficient parameters')
    }
    return fn.apply(this, args)
  }
}

作用

  1. 使函数更加灵活,粒度更小

  2. 函数参数缓存,延迟计算