JavaScript is a language of the Web. This series of articles will talk about my observations learned during my decade of software development experience with JavaScript.
Before moving further let us look at the previous articles of the series:
Every programmer wants to write good & reusable code. Curry can help to achieve that.
Context
We’ve explored functional programming aspects of Javascript like closure, similarly another useful concept is currying. Here's some important information before I move ahead with currying.
Arity
Arity refers to the number of arguments a function can accept. And, you can have functions to take n number of arguments, which is called as variadic functions. And you can leverage arguments to slice into unary, binary arguments depending upon your requirement.
Example,
- function showArgs(a, b, c)
- {
- var args = [].slice(arguments);
-
- console.log(arguments.length);
- }
Currying
Let’s cook tasty functions!
We know that extra / excess params passed to a function is ignored and not processed. Hence, it goes wasted, also if you’ve too many params passed to function it. Look at this binary function.
- function sum(x, y) {
- return x + y;
- }
It could be written as,
- var add = sum(10);
- add (20);
- add (55);
Below is the debug mode of above code where values of x, y are mentioned,
Steps:
- sum function returns a function – this is closure implementation.
- add – stores declaration as,
- function (y) {
- return x + y;
- }
- Now, whenever we invoke add (55) it calls above code and here is the value in watch.
Now if your arguments grow then you could increase and it could turn like,
- function sumFour(w)
- {
- return function(x)
- {
- return function(y)
- {
- return function(z)
- {
- return w + x + y + z;
- }
- }
- }
- }
- sumFour(1)(2)(3)(4);
Advantages of currying
- If you’re not aware of the parameters in advance, then you can store the partial result.
- It doesn’t allow more than specified number of arguments, ex-
In above function if we pass (5) as extra argument then the function will throw an error.
Disadvantages of currying
- It is not a good idea to use currying when the function has a lot of arguments.
- Some people feel it's just another representation of way we write functions.
- It is associated with partial application. We’ll cover partial application in some article as it’s beyond the scope of this article.
Please share your feedback / comments.