Function currying in JavaScript
What is function currying? The concept sounds a bit mysterious and perhaps the best explanation I could find comes from the "Pro TypeScript" book by Steve Fenton:
"Currying is a process whereby a function with multiple parameters is decomposed into multiple functions that each take a single parameter. The resulting chain of functions can be called in stages, with the partly applied stage becoming a reusable implementation of the combined function and value."
If it didn't clear anything I hope the following example will:
const converter =
(currency: string) =>
(exchangeRate: number) =>
(amount: number) =>
currency + (exchangeRate * amount).toFixed(2)
Now you may wonder what's the purpose of building such a chain of functions? If we wanted to use it to convert 5 EUR to a different currency (USD) the notation would look like this:
converter("$")(1.1)(5) // $5.50
A bit strange, if you ask me. Until we realise we can now reuse the function chain to create different currency converting functions:
const eur2usd = converter("$")(1.1);
const usd2eur = converter("€")(0.9);
eur2usd(5) // $5.50
usd2eur(5) // €4.50
Neat!
I hope this was a good demonstration of possible advantages of function currying in JavaScript.
The following example of function currying in the wild comes from Vue documentation:
getters: {
// ...
getTodoById: (state) => (id) => {
return state.todos.find(todo => todo.id === id)
}
}
store.getters.getTodoById(2)