Currying is the process of transforming a function that takes multiple arguments into a sequence of functions that each has only a single parameter. Currying is related to, but not the same as, partial application.
Let's consider the following function in JavaScript:
var add = (x, y) => x + y
We can use the definition of currying to rewrite the add function:
var add = x => y => x + y
This new version takes a single parameter, x
, and returns a function that takes a single parameter, y
, which will ultimately return the result of adding x
and y
.
var add5 = add(5)
var fifteen = add5(10) // fifteen = 15
Another example is when we have the following functions that put brackets around strings:
var generalBracket = (prefix, str, suffix) => prefix + str + suffix
Now, every time we use generalBracket
we have to pass in the brackets:
var bracketedJim = generalBracket("{", "Jim", "}") // "{Jim}"
var doubleBracketedJim = generalBracket("{{", "Jim", "}}") // "{{Jim}}"
Besides, if we pass in the strings that are not brackets, our function still return a wrong result. Let's fix that:
var generalBracket = (prefix, suffix) => str => prefix + str + suffix
var bracket = generalBracket("{", "}")
var doubleBracket = generalBracket("{{", "}}")
Notice that both bracket
and doubleBracket
are now functions waiting for their final parameter:
var bracketedJim = bracket("Jim") // "{Jim}"
var doubleBracketedJim = doubleBracket("Jim") // "{{Jim}}"