柯里化

2019-10-16 20:48:4310/1/2021, 3:34:43 AM

WHAT

柯里化是一种将使用多个参数的一个函数转换成一系列使用一个参数的函数的技术

WHY

  • 参数复用 如果是相同的参数,在计算之后不需要再次重新传参计算
  • 提前返回 多次调用多次内部判断,可以直接把第一次判断的结果返回外部接收
  • 延迟执行 缓存参数,避免重复的去执行程序,等真正需要结果的时候再执行

HOW

参数复用

常见于函数式编程(functional programing)

function add(x) {
  return function(y) {
    return function(z) {
      return x + y + z;
    };
  };
}
console.log(add(1)(2)(3)); // 6

提前返回

function addEvent() {
  if (window.addEventListener) {
    return function(el, type, fn, capture) {
      el.addEventListener(type, e => fn.call(el, e), capture);
    };
  } else {
    return function(el, type, fn) {
      el.attachEvent("on" + type, e => fn.call(el, e));
    };
  }
}

const elBind = addEvent();
elBind(document.getElementById("button"), "click", e => console.log(e), true);

延迟执行

function curryScore(fn) {
  let _allScore = [];
  return function() {
    if (arguments.length === 0) return fn.apply(null, _allScore);
    else _allScore = _allScore.concat([].slice.call(arguments));
  };
}
let allScore = 0;
const curryAllScore = curryScore(function() {
  for (let i = 0; i < arguments.length; ++i) allScore += arguments[i];
});

curryAllScore(2);
curryAllScore(3);
curryAllScore(4);
curryAllScore();
console.log(allScore);