# 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/>");// 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) {
cuf(2)(3)(4);