Reputation: 8589
I have some different statements here that I would like you to tell me if they are equivalent:
myApp.filter('myFilter', function() {
var result, i, sport, y, contains, league;
return function(sports, filterBy) {
if (angular.isUndefined(sports) || !filterBy) {
return sports;
}
filterBy = filterBy.toLowerCase();
result = [],
contains = function(haystack, needle) {
return haystack.toLowerCase().indexOf(needle) > -1;
};
for (i = 0; i < sports.length; i++) {
sport = sports[i];
if (contains(sport.name, filterBy)) {
result.push(sport);
continue;
} else {
for (y = 0; y < sport.leagues.length; y++) {
league = sport.leagues[y];
if (contains(league.name, filterBy)) {
result.push(sport);
break;
}
}
}
}
return result;
};
});
now with lodash:
myApp.filter('myFilter', function() {
var result, i, sport, y, contains, league;
return function(sports, filterBy) {
if (angular.isUndefined(sports) || !filterBy) {
return sports;
}
filterBy = filterBy.toLowerCase();
result = [],
contains = function(haystack, needle) {
return haystack.toLowerCase().indexOf(needle) > -1;
};
_.each(sports.length, function(sport) {
if (contains(sport.name, filterBy)) {
result.push(sport);
continue;
} else {
_.each(sport.leagues.length, function(league) {
if(contains(league.name, filterBy)) {
result.push(sport);
break;
}
});
}
});
just I am trying to get with the logic of lodash. I have that function in ALMOST pure JS, but once I tried to translate that to lodash, my app breaks down, so I would like to know where is the mistake ?
here I have this Plnkr with the pure js function, in the library section you will see that I have underscore
because I do not know why lodash
did not load, so, all I am trying is: translate that function into a lodash
function using _.each
instead of for loop
Upvotes: 0
Views: 898
Reputation: 1242
You wouldn't use "each" in this situation. Also in "each" you don't get "continue" or "break". For me I would use "filter" to get a filtered result. So the code should look like this:
var result = sports.filter(function(sport){
return (
contains(sport.name, filterBy)
|| (
sport.leagues && sport.leagues.some(function(league) {
return contains(league.name, filterBy)
})
)
)
})
or for lodash/underscore
var result = _.filter(sports, function(sport) {
return (
contains(sport.name, filterBy)
|| (
sport.leagues && _.some(sport.leagues, function(league) {
return contains(league.name, filterBy);
})
)
)
});
Upvotes: 1