I have a web component that is rendering a list of items and I have this method for filtering these items based in a filterBy
object that is being updated by other events and stored in the same component class.
filterBy = {
comment: '', // string
rating: [] // array of numbers
}
filterFeedback(items) {
let filteredItems = [];
const pagination = { offset: 0, limit: 10, totalCount: items.length };
const { comment, rating } = this.filterBy;
const filteringFn = (condition) => {
items.map((item) => {
if (filteredItems.length < pagination.limit) {
if (condition(item)) {
filteredItems.push(item);
}
} else {
return;
}
});
}
if (comment && (!rating || rating.length === 0) && comment !== '') {
filteringFn((item) => item.comment && item.comment.includes(comment));
} else if (!comment && rating && rating.length > 0) {
filteringFn((item) => rating.some((value) => value === item.rating));
} else if ((comment && comment !== '' )&& rating && rating.length > 0) {
filteringFn((item) => item.comment && item.comment.includes(comment) && rating.some((value) => value === item.rating));
} else {
filteredItems = items ? items.filter((item, i) => i < pagination.limit) : [];
}
return filteredItems;
}
I was analyzing this code and trying to make it more clear and readable. I think the filteringFn
saves me a lot of code duplication but still, I found the conditionals unreadable. Besides, it's not scalable in case I'd like to add more filters.