美文网首页我爱编程
函数的柯里化

函数的柯里化

作者: zjh111 | 来源:发表于2018-04-14 17:41 被阅读0次

实质返回一个函数
例如

function add(a, b) {
    return a + b;
}

function curryingAdd(a) {
    return function(b) {
        return a + b;
    }
}
curryingAdd(1)(2)  //3
function currying(){
    let arg =[]
    function add(){
        if(arguments.length === 0){
            return arg.reduce((a,b)=>a+b)
        }
        arg = arg.concat([].slice.call(arguments))
        return add
    }
    return add
}

let add = currying()

add(1,2)(3)() //6

以上是延迟计算,只有到最后一步才会计算。

柯里化的作用 1. 参数复用;2. 提前返回;3. 延迟计算/运行。

“提前返回”,很常见的一个例子,兼容现代浏览器以及IE浏览器的事件添加方法。我们正常情况可能会这样写:
var addEvent = function(el, type, fn, capture) {
if (window.addEventListener) {
el.addEventListener(type, function(e) {
fn.call(el, e);
}, capture);
} else if (window.attachEvent) {
el.attachEvent("on" + type, function(e) {
fn.call(el, e);
});
}
};
上面的方法有什么问题呢?很显然,我们每次使用addEvent为元素添加事件的时候,(eg. IE6/IE7)都会走一遍if...else if ...,其实只要一次判定就可以了,怎么做?–柯里化。改为下面这样子的代码:

var addEvent = (function(){
if (window.addEventListener) {
return function(el, sType, fn, capture) {
el.addEventListener(sType, function(e) {
fn.call(el, e);
}, (capture));
};
} else if (window.attachEvent) {
return function(el, sType, fn, capture) {
el.attachEvent("on" + sType, function(e) {
fn.call(el, e);
});
};
}
})();
初始addEvent的执行其实值实现了部分的应用(只有一次的if...else if...判定),而剩余的参数应用都是其返回函数实现的,典型的柯里化。
以上摘自张鑫旭 http://www.zhangxinxu.com/wordpress/2013/02/js-currying/

相关文章

网友评论

    本文标题:函数的柯里化

    本文链接:https://www.haomeiwen.com/subject/sgkkkftx.html