September 05, 2016
This in turn leads to tighter, more compact code.
Here is a simple example of a function that expects two arguments, a, and b, and returns the sum of the two.
This function can be curried to return a function.
With the curried function above, functions can be built that are partially applied as such:
Application in the real world
Recently at my current employer, Jet, I was working on building the Buy Box (as seen below) for the product details page (the page that lists a products description, and pricing breakdown). After working out a potential solution for building this component I was able to refactor my solution and use currying to build make the code more efficient.
Depending on the product, Jet allows a user to select from various discounts, including opting out of free returns, using a debit card, and a combination of the two.
Each one of these different discounts uses a base price and then subtracts the discounts accordingly to give the final price.
In the example above:
waive returns: savings of .09 for a final price of $9.10
debit card: savings of .14 for a final price of $9.05
combination of the two: savings of .23 for a final price of $8.96
One-way to write the functions to generate each one of the savings are…
With this solution, there is a lot of code repeat, and the code isn’t very DRY. All three functions expect the startingPrice argument to be passed in, and each is returning the startingPrice subtracted from the savings passed in. In addition, if more savings were added in the future this code would continue to get bloated.
To make this code tighter, and allow for additional savings to be added in the future, we can leverage currying, as well as some ES6 operators to our advantage.
What once took 3 functions to accomplish, has now been achieved with this one calcSavings function. With currying the functions can now be called as so:
Here is what the break down of the waiveReturnsAndDebit call will look like:
Should Jet in the future look to add more discounts, because of currying (and with the help of reduce) this function allows for any number of discounts to be added, without having the change the logic for how they are deducted from the starting price.
By utilizing currying, functions become smaller, code becomes tighter, and repitiion decreases.