Without reading the for implementation carefully it's much harder to verify:
* You're looping from start to finish * Over each element * You're only adding the items to the new list that match the conditions.
That all said, I think this swap is only a good idea if the thing you're swapping with is commonly used. Which admittedly is a chicken-and-egg problem, but does largely exclude non-library function transformations or one-off transformations.
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');