![]() |
VOOZH | about |
Currying and Function composition are essential concepts in functional programming that enhance code reusability and readability.
Lodash provides more powerful utilities to implement both concepts effectively. In this article, we will understand curry and function composition using Lodash flow.
Table of Content
Currying is a technique of breaking down a function that accepts multiple arguments into a sequence of functions that each take a single argument. This allows for partial application of arguments.
Syntax:
const curriedFunction = _.curry(originalFunction);Example: In this example, we will add function takes three arguments but is transformed into a curried function using _.curry(). This allows us to create a partially applied function, addFive which takes the first argument (5) and later accepts the remaining arguments (3 and 2) to compute the final result (10).
Output
10Function composition is the process of combining multiple functions to create a new function. The new function executes the provided functions in sequence.
Syntax:
const composedFunction = _.flow([function1, function2, ...]);Example: Here, the double function and addFive the function is composed using _.flow() creating a new function, doubleThenAddFive. When we call this composed function with an input of 3, it first doubles the value (resulting in 6) and then adds five, yielding the final output of 11.
Output
11We can also combine currying with function composition for more complex scenarios, allowing for flexible function applications.
Syntax:
const composedFunction = _.flow([
_.curry(functionToCurry),
functionToCompose
]);
Example: Here, the curried multiply the function is partially applied with the first argument (2) and then composed with the addOne Function. When called with additional arguments (3 and 4), it first multiplies them (2 * 3 * 4 = 24) and then adds one, resulting in the final output of 25.
Output
25