Is there a method to reduce the requirement for if-conditions in this situation?

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).

Answer №1

Here's a condensed version of the logic into one filter function that might be useful:

.filter(property => {
      if(
        (
          this.userSettings.getAppSetting("filterMaxPrice", "number") == 0 ||
          property.price <= this.userSettings.getAppSetting("filterMaxPrice", "number")
        ) &&
        (
          property.incomeCategory == this.userSettings.getAppSetting("filterIncomeClass", "string") ||
          this.userSettings.getAppSetting("filterIncomeClass", "string") == "none"
        ) &&
        (
          property.numberOfRooms >= this.userSettings.getAppSetting("filterMinRooms", "number")
        ) &&
        (
          property.numberOfBedrooms >= this.userSettings.getAppSetting("filterMinBedrooms", "number")
        )
      ) {
          return property;
      }
  })

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The hue of the knob is unchangeable once the server data request is made

Upon receiving data from the server request, I am unable to update the color of the knob to match the image provided at this link screencast. Below is my code: JavaScript Code $scope.options = { /* knob option */ }; $http .get(url) .then(functio ...

Extract keys from a list of interface keys to create a sub-list based on the type of value

Issue Can the keys that map to a specified value type be extracted from a TypeScript interface treated as a map? For example, consider the WindowEventMap in lib.dom.d.ts... interface WindowEventMap extends GlobalEventHandlersEventMap, WindowEventHan ...

What is the best way to generate a dynamically interpolated string in JavaScript?

I'm currently developing a reusable UI component and am exploring options to allow the user of this component to provide their own template for a specific section within it. Utilizing TypeScript, I have been experimenting with string interpolation as ...

"Adjusting the position of an Ionic Menu on-the-fly

As I strive to update the Ionic 3 Menu side dynamically when the user changes the language, a challenge arises for RTL languages where the menu needs to be on the right instead of the default left. To tackle this issue, I have subscribed to the TranslateS ...

Issues arise when attempting to use AngularJS validators in conjunction with another directive

I created a directive called "uniqueCheck" that validates the ngModel based on whether the value is already in a list or not. Everything works fine when the directive is used directly on an input tag. However, when used on a custom directive that contains ...

What is the best way to retrieve all the keys from an array?

I am looking to retrieve the address, latitude, and longitude data dynamically: let Orders= [{ pedido: this.listAddress[0].address, lat: this.listAddress[0].lat, lng: this.listAddress[0].lng }] The above code only fetches the first item from the lis ...

I successfully installed Angular CLI, but I'm encountering an error indicating that it is not recognized in the command prompt

Recently, I installed Nodejs, followed by npm, and then angular cli as per instructions. However, when I run the command "ng --version" in Windows cmd or git bash, it returns: ng is not recognized as an internal or external command, operable program o ...

Can Typescript classes be hoisted if I use two classes in my code?

Exploring Class Definitions Certain Rules to Comply With Ensuring that the class is defined in advance helps avoid errors. class Polygon { log() { console.log('i am polygon'); } } const p = new Polygon(); // Expected: no errors p.log(); U ...

What is the reason for the failure of the "keyof" method on this specific generic type within a Proxy object created by a class constructor?

I'm encountering difficulties when utilizing a generic type in combination with keyof inside a Proxy(): The following example code is not functioning and indicates a lack of assignable types: interface SomeDataStructure { name?: string; } class ...

What is the process of displaying JSON response data in AngularJS?

I am attempting to retrieve URL information using get_meta_tags in Laravel and then display it in my AngularJS application. However, the issue is that the response is returned in the following format: Array ( [title] => Mercy Badshah Full HD [d ...

What is the process for retrieving the information sent from the client application to the jsreport server?

I want to create a downloadable pdf report through my angular application using jsreport. The client app makes a POST request passing sample data to the report server in this manner. $http.post('http://localhost:5488/api/report', { ' ...

Utilizing props in styled components with Emotion-js and Typescript is not feasible

Check out this simple React component I created: import React, { ReactChild, ElementType } from 'react' import styled from '@emotion/styled' type WrapperPropsType = { size?: SizeType } type ButtonPropsType = { as?: ElementType< ...

Enforce the splicing of the ng-repeat array with the utilization of track by

Our app incorporates a task list that can potentially grow to a substantial size. The main task list is accompanied by a sidebar, where selected tasks can be edited using a different controller (TasksSidebarCtrl instead of TasksCtrl which handles the list ...

Ensuring the proper typescript type for assigning a value in react-hook-form

I'm encountering an issue when trying to pass the function setValue() down to a child component. The error message I receive is: Type 'UseFormSetValue<Inputs>' is not assignable to type 'UseFormSetValue<Record<string, any> ...

Exploring Angular's XML Parsing and Pagination Features

Struggling to integrate these two AngularJS apps or modules? I've tried everything and can't seem to make it work. Check out the code here: 1) Display and list XML files using ng-repeat 2) Implement pagination using an AngularJS script ...

How can I confirm if a class is an instance of a function-defined class?

I have been attempting to export a class that is defined within a function. In my attempts, I decided to declare the class export in the following way: export declare class GameCameraComponent extends GameObject { isMainCamera: boolean; } export abstra ...

Displaying a two-dimensional array from a JSON file using AngularJS ng-repeat

Looking at this HTML file, I am trying to display a 2D array from the json-$scope.listOfIngredient <div class="ingredientMapping" ng-repeat="IngredientMapping in listOfIngredient track by $index"> <ul> <!-- BEGIN: Inner ngRep ...

Inconsistent behavior between Chrome and Firefox when using AngularJS $resource GET method: success in Chrome but error

I am currently working on a simple custom GET request in Angular using $resource angular.module('myApp') .factory('MyService', function($resource){ return $resrouce('some url', {}, { list: {method:'G ...

Illustrative demonstration of Vue with TypeScript

I am currently working on developing a HelloWorld application using Vue.js and TypeScript. index.html <script data-main="app.js" src="node_modules/requirejs/require.js"></script> <div id="app">{{text}}</div> app.ts import Vue f ...

Troubleshooting Problem: Difficulty accessing Controller in AngularJS Module

I am facing difficulties with communication between my application and a module that I have developed. Below is the AngularJS module that I created. (function (document, window) { 'use strict'; var piCart = angular.module('piCart& ...