Source:http://tech.pro/tutorial/2011/functional-javascript-part-4-function-currying
Currying is the process of transforming a function that takes multiple arguments to a function that takes just a single Argument and returns another function if any arguments is still needed.
Function currying allows and encourages you to compartmentalize complex functionality into smaller and easier to reason AB Out parts. These smaller units of logic is dramatically easier to understand and test, and then your application becomes a nice and Clean composition of the smaller parts.
var function (from, to, msg) { alert (["Hello" + to + ",", MSG, "Sincerely,", "-" + from].join ("\ n"));
var // returns function (A,B,C) var // returns function (c) Sendmsgfromjohntobob ("Come join the curry party!" //= "Hello Bob, Come join the curry party! Sincerely,-John.
If We know the number of arguments, we can do manual currying.
//uncurriedvarExample1 =function(A, B, c) {//Do something with a, B, and C};//CurriedvarExample2 =function(a) {return function(b) {return function(c) {//Do something with a, B, and C }; };};
A simple helper functionsub_curry
function /* */) {var args = [].slice.call (arguments, 1) ; return function () { return fn.apply (This, Args.concat (ToArray (arguments)); };}
A complete curry function
functionCurry (FN, length) {//capture FN ' s # of parametersLength = Length | |fn.length; return function () { if(Arguments.length <length) { //Not all arguments has been specified. Curry once more. varCombined =[Fn].concat (ToArray (arguments)); returnLength-arguments.length > 0? Curry (Sub_curry.apply ( This, combined), length-arguments.length): Sub_curry.call ( This, combined); } Else { //All arguments has been specified, actually call function returnFn.apply ( This, arguments); } };}Codewars-a Chain Adding function
We want to create a function, that would add numbers together when called in succession.
add(1)(2);// returns 3
We also want to is able to continue to add numbers to our chain.
add(1)(2)(3); // 6add(1)(2)(3)(4); // 10add(1)(2)(3)(4)(5); // 15
And so on.
A single call should return the number passed in.
add(1) // 1
And we should is able to store the result and reuse it.
var addTwo = add(2);addTwo // 2addTwo(3) // 5addTwo(3)(5) // 10
We can assume any number being passed in'll be valid JavaScript number.
function Add (n) { varfunction(x) { return Add (n+x) } function() { return n } return F}
Function currying in JavaScript