-
-
Save lucagrulla/67661d178e4f83812a3d to your computer and use it in GitHub Desktop.
Partial functions in Javascript with bind
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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