Currying

How to implement an add funtion?

1
2
3
4
function add(x, y) {
return x+y;
}
add(1, 3)===4//true

How to implement add(1)(3) === 4?

1
2
3
4
5
function add(x) {
return function(y) {
return x+y;
}
}

How to implement add3(2) === 5?

1
2
3
4
5
6
7
8
function currying(fn, ...args1) {
return function(...args2) {
fn(...args1, ...args1);
}
}

var increment = currying(add, 1);
increment(5)===6//true

How to implement infinite arguments?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function trueCurrying(fn, ...args1) {
if(args1.length>=fn.length) return fn(...args1);
return function(...args2) {
return trueCurrying(fn, ...args1, ...args2);
}
}

function triAdd(x, y, z) = {
return x+y+z;
}

var curryAdd = trueCurrying(triAdd);
curryAdd(1,2,3)===6//true;
curryAdd(1,2)(3)===6//true;
curryAdd(1)(2)(3)===6//true;