Let's see a practical case of our tiny functional toolbox.
Here, the object we will use :
let pets = [
{
petname : "Bill",
breed : "poodle",
weight: 12,
owner : {
ownername : "Paul",
contribution : {
amount : 32,
payed : false
},
address : {
city : "Paris"
}
}
},
{
petname : "Maya",
race : "pointer",
weight: 27,
owner : {
ownername : "Henri",
contribution : {
amount : 12,
payed : true
},
address : {
city : "London"
}
}
},
{
petname : "Ooper",
race : "setter",
weight: 20,
owner : {
ownername : "Nicolas",
contribution : {
amount : 12,
payed : true
},
address : {
city : "London"
}
}
}
]
Say you want the list of all the cities.
With our tools, we can create a function which, when given a 'string path' for a property, returns the property value.
Let's name this function pick.
Here is a possible implementation :
function pick (path) {
let pickprops = map((prop) => pickprop(prop), path.split("."));
return pipe(...pickprops);
}
We can now create a function, which will return a 'city value' for a single entry.
let pickCity = pick("owner.address.city");
Nice isn't it ?
Now we can explicitely list all the cities :
let pickCity = pick("owner.address.city");
let cities = map(pickCity)(pets);
// or
cities = map(pickCity, pets);
console.log(cities)
I like this one too :
let cityMapper = map(pick("owner.address.city"));
let cities = cityMapper(pets);
console.log(cities)
We can go a step further and feel the spirit of functional programming :
let mapper = compose(map, pick);
let citymapper = mapper("owner.address.city")
cities = citymapper(pets)
console.log(cities)
Result :
You can play with a demo here Demo
Hope you enjoyed...
Top comments (0)