After revisiting this previous inquiry, I successfully implemented multiple filters on my observable, based on the user's chosen filters.
However, the issue arises from the uncertainty of whether a filter is applied and the varying behavior of each filter; some are numerical, while others are string-based.
Here is how I retrieve my observable:
getProperties(): Observable<Property[]> {
return this.http.get<Property[]>(this.url);
}
and apply the dynamic filters in the following manner:
filterAndSort() {
let count = 0;
return this.getProperties()
// Filter properties where price is greater than or equal to the minimum price
.map(properties => properties.filter((property) => {
if(property.price >= this.userSettings.getAppSetting("filterMinPrice", "number")) {
return property;
}
})
.filter((property) => {
// Return all properties if max price is not set (0)
if(this.userSettings.getAppSetting("filterMaxPrice", "number") == 0) {
return property;
}
// Filter properties where price is lower than or equal to the maximum price
else if(property.price <= this.userSettings.getAppSetting("filterMaxPrice", "number")) {
return property;
}
})
.filter((property) => {
if(property.incomeCategory == this.userSettings.getAppSetting("filterIncomeClass", "string")) {
return property;
} else if (this.userSettings.getAppSetting("filterIncomeClass", "string") == "none") {
return property;
}
})
.filter((property) => {
if(property.numberOfRooms >= this.userSettings.getAppSetting("filterMinRooms", "number")) {
return property;
}
})
.filter((property) => {
if(property.numberOfBedrooms >= this.userSettings.getAppSetting("filterMinBedrooms", "number")) {
return property;
}
})
.sort((a: Property, b: Property) => {
// Sorting logic here
}
))
}
While this implementation works, I believe there could be a more efficient solution to avoid repetitive filter()
calls. By reducing the number of if-conditions and utilizing return property;
only once within each condition, the code could be much cleaner. (It should be noted that more filter options will be added in the future, potentially making this process even messier if not optimized).
Any recommendations for improving this setup?
(To clarify, I am working with NativeScript/Angular/TypeScript in this context).