Javascript: how to create partial functions
Currying and partial application functions are very powerful techniques widely adopted by many functional langagues.
If you work with Javascript you can use the core function bind to easily create partial applications.
Let’s look at an example.
We have an array of objects:
and a function that given a city object and a specific country returns true if the city belongs to the given country:
What if we’d like to filter the array looking for cities that are in a specific country?
A partial function is a good approach to solve the problem, and bind makes the creation of it very simple.
The syntax of bind is the following:
Where the first parameter is the value we want to bound the this keyword to when the created function is invoked while the others are the actual parameters of the bound function.
We can now use the partial function UKCity as argument of the filter function:
In the example the creation of a partial application function allows us to seamlessly compose our initial isIn function with a higher order function like filter to achieve more sophisticated outcomes.
A gist with the whole example code is available here.