Skip to content

Instantly share code, notes, and snippets.

@lucagrulla

lucagrulla/bind.js Secret

Last active Aug 29, 2015
Embed
What would you like to do?
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
You can’t perform that action at this time.