currying
Currying is a transformation of functions that translates a function from callable as f(a, b, c) into callable as f(a)(b)(c).
we can transform a function with multiple arguments into a sequence of nesting functions.
It returns a new function that expects the next argument inline.
It keeps returning a new function (that expects the current argument, like we said earlier) until all the arguments are exhausted.
The arguments are kept
"alive"
(via closure) and all are used in execution when the final function in the currying chain is returned and executed.
Example Description:
The result of
curry(func)
is a wrapperfunction(a)
.When it is called like
carriedSum(1)
, the argument is saved in the Lexical Environment, and a new wrapper is returnedfunction(b)
.Then
carriedSum(1)(2)
finally callsfunction(b)
providing2
, and it passes the call to the original multi-argumentsum
.
Advanced currying:
when the function call is completed with argument will return the function.
when function is call is completed without argument will return the sum of all arguments.
Last updated