Skip to content
On this page

函数柯理化

张鑫旭-JS中的柯里化(currying)

柯理化的作用

  • 参数复用
  • 提前返回
  • 延迟计算/运行

参数复用

js
function url_curring(protocol) {
  return function (host, path) {
    return protocol + host + path
  }
}

const url_https = url_curring('https://')

const url1 = url_https('www.baidu.com', '/aaa') // https://www.baidu.com/aaa 
const url2 = url_https('www.baidu.com', '/bbb') // https://www.baidu.com/bbb
const url3 = url_https('www.baidu.com', '/ccc') // https://www.baidu.com/ccc

提前返回

浏览器兼容判断 使用立即执行函数判断

函数里面返回函数

js
const addEvent = (function () {
  if (window.addEventListener) {
    return function (element, type, fn, capture) {
      element.addEventListener(type, function (e) {
        fn.call(element, e)
      }, capture)
    }
  } else if (window.attachEvent) {
    return function (element, type, fn) {
      element.attachEvent('on' + type, function (e) {
        fn.call(element, e)
      })
    }
  }
})()

延时调用

实现 add(1)(2)(3)

利用 toString 实现:

js
function argsSum(args) { return args.reduce((pre, cur) => { return pre + cur }) }

function add(...args1) {
  let sum1 = argsSum(args1)
  let fn = function (...args2) {
    let sum2 = argsSum(args2)
    return add(sum1 + sum2)
  }
  fn.toString = function () { return sum1 }
  return fn
}

reduce 实现:

js
function add(...args) {
  let sum = args.reduce((acc, cur) => acc + cur)

  return function (...nextArgs) {
    return nextArgs.length
           ? add(sum, ...nextArgs)
           : sum
  }
}

高颜值:

js
var curry = fn =>
  judge = (...args) =>
    args.length === fn.length
    ? fn(...args)
    : (arg) => judge(...args, arg)