13 ms·
That is certainly something I've also come across. This kind of functional style is very readable once you understand it, but it does have a learning curve jus
by PJDK 10y ago
That is certainly something I've also come across. This kind of functional style is very readable once you understand it, but it does have a learning curve just like learning what "for(var i = 0; i< length; i++)" means.
I actually did a little presentation to the team about how to refactor a for loop to an self implemented where/filter function to explain the connection. For me, realising that all the where was doing (or at least potentially, there might be some behind the scenes optimisations going on) was passing in the condition for an IF in a FOR loop suddenly clarified everything for me.
In case anyone's interested, this is these are the code steps (javascript)
var people = [{name: 'bob', gender: 'male'}, {name: 'dave', gender: 'male'}, {name: 'sarah', gender: 'female'}];
var getAllMen = function(population) {
var returnList = [];
for(var i = 0; i< population.length; i++){
if(population[i].gender === 'male'){
returnList.push(population[i]);
}
}
return returnList;
}
var males = getAllMen(population);
___
var getAllMen = function(population) {
var returnList = [];
for(var i = 0; i< population.length; i++){
if(isMan(population[i]){
returnList.push(population[i]);
}
}
return returnList;
}
var isMan = function(person){
return person.gender === 'male';
}
var males = getAllMen(population);
___
var filter = function(anyOldList, filterCondition){
var returnList = [];
for(var i = 0; i< anyOldList.length; i++){
if(filterCondition(anyOldList[i]){
returnList.push(anyOldList[i]);
}
}
return returnList;
}
var isMan = function(person){
return person.gender === 'male';
}
var males = filter(population, isMan);
var females = filter(population, function(person){
person.gender === 'female';
});
var females = filter(population, person => person.gender === 'female');
var females = filter(population, x => x.gender === 'female');