Reputation: 2378
I have a few .filter
functions, two of which are below. These both work and do what they are meant to. The problem I've got is that they take a bit of time to do the filtering as they have to iterate over the records that come from the backend. The way this is currently set up is that the backend returns all the records which are around 400 in total. Don't know why its not just returning the first page of results (or first few pages), returning all results just to make it easy to paginate through all the records seems a bit much but that's not my decision.
When checking various checkboxes the filtering is performed on the selected checkboxes, it feels a bit slow as when one of the checkboxes is checked it takes a short but noticeable period of time to tick the checkbox as the filtering is being performed.
How can I optimize this code so that it runs faster? Would using underscore.js
be worth using for this purpose?
.filter('rangeFilter', function() {
return function(hotelResults, price ) {
var filtered = [];
var priceMin = parseInt(price.min);
var priceMax = parseInt(price.max);
angular.forEach(hotelResults, function(hotel) {
if((hotel.Price >= priceMin && hotel.Price <= priceMax)) {
filtered.push(hotel);
}
});
return filtered;
};
})
.filter('ratingsFilter', function() {
return function(hotelResults, ratings) {
filteredResults = []
angular.forEach(hotelResults, function(hotel) {
angular.forEach(ratings, function(rating) {
if (hotel.Rating === rating.value && rating.selected === true) {
filteredResults.push(hotel)
}
})
})
return filteredResults;
}
})
Upvotes: 1
Views: 115
Reputation: 10849
For the first snippet I don't really see an optimization.
For the second one though, I guess you can improve time complexity.
This improves time complexity from O(n.m)
to O(n + m)
.filter('ratingsFilter', function() {
return function(hotelResults, ratings) {
var filteredResults = [];
var ratingsHash = {};
angular.forEach(hotelResults, function(hotel) {
if (!(hotel.Rating in ratingsHash)) {
ratingsHash[hotel.Rating] = [];
}
ratingsHash[hotel.Rating].push(hotel);
});
angular.forEach(ratings, function(rating) {
if ((rating.value in ratingsHash) && rating.selected === true) {
var hotels = ratingsHash[rating.value];
Array.prototype.push.apply(filteredResults, hotels);
}
})
return filteredResults;
}
})
Upvotes: 2