xamples
epeat
ode
pproach
ptimize
est
a, b
curry
a
b
a b
Formal Definition:
"Currying is the process by which a function of N arguments is implemented as N single-argument functions such that first of them takes in the first argument and returns a function which takes in the 2nd argument and so on, until the Nth single-argument function finally returns the value of the multi-argument function being implemented."
function addAllFour(var1, var2, var3, var4) {
return var1 + var2 - var3 * var4;
}
var curriedDoSomething = curry(doSomething) // closure memory -> []
var firstReturn = curriedDoSomething(1) // closure memory -> [1]
var secondReturn = curriedDoSomething(2) // closure memory -> [1 , 2]
var thirdReturn = curriedDoSomething(3) // closure memory -> [1, 2, 3]
var fourthReturn = curriedDoSomething(4) // -9 (1 + 2 - 3 *4)
function doMath(a, b, c, d) {
return a + b - c * d;
}
var curried = curry(doMath);
var makeOne = curried(1);
var makeTwo = makeOne(2);
var returned1 = makeOne(3, 4, 5); // -16 (1 + 3 - 4 * 5)
var returned2 = makeTwo(4, 5) // -17 (1 + 2 - 4 * 5)
function curry( originalFunc ) {
var originalLength = originalFunc.length;
function resolver() {
var memory = Array.prototype.slice.call( arguments );
var whatToReturn = function() {
var next,
args = Array.prototype.slice.call( arguments ),
copy = memory.concat(args);
if (copy.length >= originalLength) {
next = originalFunc;
} else {
next = resolver;
}
return next.apply(null, copy);
};
return whatToReturn;
}
return resolver();
}
function doMath(a, b, c, d) {
return a + b - c * d;
}
var steph1 = curried(/* Do Something */ 1);
var steph2 = steph1(1, 2, 3) // 0 (1 + 2 - 3 * 1)