The currying function takes a function with multiple arguments into a sequence of functions, each with only a single argument.
Currying is named after mathematician Haskell Curry.
Using the currying function, an n-ary function turns into a unary function.
Example of n-ary function and turn into curing function (code):
`const multiargFunction = (a,b,c) => a + b + c;
console.log(multiargFunction(1,2,3)) //6
const curryFunction = (a) => (b) => (c) => a + b + c;
console.log(curryUnaryFunction(1)); // returns a function: (b) => (c) => a + b + c
console.log(curryUnaryFunction(1)(2)); // returns a function: (c) => a + b + c
console.log(curryUnaryFunction(1)(2)(3)); // returns the number 6 `
Curried functions are great to improve code reusability and functional composition.
I hope you like our post, please feel free to comment with your suggestion or problems you face in programming.
Top comments (1)
I find currying is handy when I'll eventually need access to a value that isn't quite in scope/not available yet.
My most recent use case was when I needed an on click handler. I needed to be able to reset my form and do other stuff on a button click, but the reset form function wasn't available until the form rendered.
So I just created a function that takes the reset form and returns an on click listener. I found it a nice way to keep things tidy and near the other relevant stuff in scope.
Here is the React snippet: