javascript科里化(Currying)

 首先Wiki里对Curring(科里化)的定义:

Currying is the technique of transforming a function that takes multiple arguments 
in such a way that it can be called as a chain of functions each with a single argument.
意思是:将多拥有多个参数的函数形式转化为拥有单一参数的函数形式.
比如下面是一个普通求和函数:

 

function add(x, y) {
    return x + y;
}
document.write("add(3, 4) == " + add(3, 4));


 

下面看下这个普通函数科里化的例子:

 

function add(x, y) {
    if(x != null && y != null) return x + y; // 如果x,y都不为null.则返回x + y;
    else if(x != null && y == null) {
        return function(y) {
            return x + y;
        }
    }else if(x == null && y != null){
        return function(x) {
            return x + y;
        }
    }
}

document.write("add(3, 4) == " + add(3, 4) + "<br/>");
document.write("add(3)(4) == " + add(3)(4) + "<br/>");// add(3)得到的是一个add的科里化函数


 

最后给出一个通用的科里化转化函数:

//===========================
//
//    ==== Common Curring ====
//
//===========================
function Curring(func) {
    return function() {
        var args = Array.prototype.slice.call(arguments, 0);
        if(args.length < func.length){ // 如果形参小于实参参数
            return function(){
                var _args = args.concat(Array.prototype.slice.call(arguments, 0));  // 取得参数
                return Curring(func).apply(this, _args);   // 然后递归调用函数,获取所有参数
            }
        }else {
            return func.apply(this, args);
        }
    }
}

// ==== the Common function ====
function f(x, y, z) {
    alert([x, y, z])
}
var cuf = Curring(f);
cuf(2, 3, 4);
cuf(2, 3)(4);
cuf(2)(3)(4);


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值