The nested ternary operation should be extracted into a separate statement, according to Sonar Issue

Can someone help me with fixing this sonar problem?

public sortDataByPredicate(dataList: any[], predicate: string): any[] {
    return dataList.sort((a: string, b: string) => 
      (a[predicate] > b[predicate]) ? 1 : ((b[predicate] > a[predicate]) ? -1 : 0));

Answer №1

This is the proposed solution:

  public sortByPredicate(dataList: any[], predicate: string): any[] {
    return dataList.sort((a: string, b: string) => {
      if ((a[predicate] > b[predicate])) {
        return 1;
      } else {
        if (b[predicate] > a[predicate]) {
          return -1;
        } else {
          return 0;
        }
      }
    });
  }

Some else statements are unnecessary; this presents a more concise form.

  public sortByPredicate3(dataList: any[], predicate: string): any[] {
    return dataList.sort((a: string, b: string) => {
      if ((a[predicate] > b[predicate])) {
        return 1;
      }
      if (b[predicate] > a[predicate]) {
        return -1;
      }
      return 0;
    });
  }

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

Transform the elements in an ArrayList into a single string separated by commas

Greetings fellow developers, After successfully deserializing an ArrayList from a text file in my application, I now have a list of Strings. In order to enhance the design, I aim to combine the contents of this ArrayList into a single organized string wit ...

"Utilizing Angular's RxJS to efficiently filter an observable

I am currently attempting to filter a stream of products using an array of filters, but I am unsure of the best approach. Let me clarify my goal: I want to store the filtered result in the variable filteredProducts. To perform the filtering, I need to ite ...

Testing the functionality of an event that is not linked to an event emitter

Below is the code snippet I'm working with: private client: any; this.client = mqtt.connect(url, mqttOptions); this.client.on('message', (topic: string, message: string) => { console.log('came inside onMessage'); ...

The error message "Property 'list' is not found on type 'void' React - Material UI" indicates that the 'list' property is not recognized

Currently, I am facing an issue while working with Material UI and React Typescript. The error message I receive is "Property 'list' does not exist on type 'void'" when attempting to use makeStyles and createStyles to remove padding. It ...

Keeping the Angular Material sidenav constantly expanded on desktop screens

I just started learning Angular and I'm attempting to implement the sidenar component from Angular Material (current version). Here is the code snippet inside the main-nav component: <mat-sidenav-container class="sidenav-container" autosize> ...

Encountering a TypeScript type error when returning a promise from a function

I currently have a scenario in which there is a function that checks if user whitelisting is required. If not, it calls the allowUserToLogin function. If yes, it then checks if a specific user is whitelisted. If the user is not whitelisted, an error is thr ...

Steps for importing jQuery typings into TypeScript:1. First, install the jQuery

I've searched for similar questions, but haven't found one that matches my issue. Can someone help me figure out what to do next? In my Visual Studio project, I used package.json to download jquery typings into the node_modules folder: { "ver ...

Can an array be transformed into an object using a function?

I am looking to convert a string into an object in JavaScript. var api_response = { key: "settings.options.height", val: 500 }; keys = api_response.key.split('.'); var settings = { options: { height: 0 } }; I am unsure how to update t ...

The `react-router-dom` in React consistently displays the `NotFound` page, but strangely, the active class for the home page does not get

Currently, I am utilizing "react-router-dom": "^6.4.1" in my application and encountering two main issues: Upon navigating to another page, the home page retains the active class, resulting in both the new page and the home page disp ...

Automatically populating additional fields in JavaScript/React by taking information from the initial field

1. I am working with an array called "listOfPaysIndexes", which contains 12 indexes. My goal is to use this array to iterate through and display 12 DateInput fields. 2. Each of these fields can be clicked on to select a date. 3. Once a date is chosen in ...

Managing the state of a component in Angular

In the process of uploading files to blob storage using a component, I have encountered an issue with my side bar navigation. Specifically, I am looking for a method to ensure that the progress of file uploads is maintained even when switching between co ...

What is the best way to simulate a static variable in JavaScript unit testing?

After running the karma coverage test, I achieved a coverage of 99.3%. To reach 100%, I require assistance in testing the else part of the function below: createCurrencyUnits(): void { var keys = Object.keys(ObjectsDomainConstants.CURRENCY_UNITS); for (va ...

Is it possible to verify if the @Output is correctly wired up within an Angular component?

When working with Angular and TypeScript, it is possible to access the bound @Input values in the ngOnInit method of a component. However, there isn't a straightforward way to check if a particular @Output event binding has been set up on the componen ...

Angular 2 failing to display background images

I have been working on an Angular 2 app with just one component. I recently tried to set a background image for the entire page using the following code: app.component.html <dashboard class="dash"></dashboard> app.component.css .dash { b ...

C++ implementation of Sudoku solving through object-oriented programming techniques

My sudoku solving program is being compiled, but I keep encountering a "segmentation fault" error. Could someone please assist me in resolving this issue and help clarify why I am receiving the segmentation error when everything appears to be coded corre ...

Seamlessly Syncing Sessions between Ionic3 App and Joomla

I currently have an Ionic 3 App integrated with a Joomla Backend using api.php which contains all the necessary functions. My app utilizes Http and Storage modules to communicate with api.php. I am able to successfully make requests such as user/login and ...

Revamping an npm package on GitHub

Currently, I am managing a project that has gained popularity among users and has received contributions from multiple individuals. The next step I want to take is to convert the entire library into TypeScript, but I am unsure of the best approach to ach ...

Importing a Dynamic Array in a SQL statement using the IN clause

I have an array called $f_array that is populated with values using while loops and SQL queries. Now, I need to incorporate the values from this array into a SQL query. $sql="SELECT * FROM comment WHERE uname IN ($f_array) ORDER BY ID DESC"; After loadi ...

Is it possible to create an instance in TypeScript without using class decorators?

As per the definition on Wikipedia, the decorator pattern enables you to enhance an object of a class with additional functionalities, such as: let ball = new BouncyBall(new Ball()) The Ball object is adorned with extra features from the BouncyBall class ...

Can shell commands be run within an Angular Schematic?

I'm exploring the idea of creating a custom schematic that can automatically launch a Node microservice alongside an Angular app when using "ng serve". I'm wondering if it's feasible to achieve this directly within the schematic, or if I wou ...