Skip to content

Instantly share code, notes, and snippets.

@lucagrulla
Last active August 29, 2015 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucagrulla/67661d178e4f83812a3d to your computer and use it in GitHub Desktop.
Save lucagrulla/67661d178e4f83812a3d to your computer and use it in GitHub Desktop.
Partial functions in Javascript with bind
var cities = [{name: "Paris", country: "France"}, {name: "London", country: "UK"}, {name: "Rome", country: "Italy"},{name: "Manchester", country: "UK"}];
var isIn = function(country, city) {
return city.country === country;
};
isIn("UK", {name: "London", country: "UK"}); //true
var UKCity = isIn.bind(null, "UK");//don't need to set the this keyword, just passing null
//UKCity can be used like this:
UKCity({name: "London", country: "UK"}); //true
//UKCity is now a perfect fit to be used with a higher order function
var UKCities = cities.filter(UKCity);
//UKCities === [{name: "London", country: "UK"}, {name: "Manchester", country: "UK"}]
//get the list of the Italian cities is as simple as:
cities.filter(isIn.bind(null, "Italy"));
//[{name: "Rome", country: "Italy"}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment