Home > database >  Extract this nested ternary operation into an independent statement. Sonar Issue
Extract this nested ternary operation into an independent statement. Sonar Issue

Time:01-10

I'm unable to resolve this sonar issue.

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

CodePudding user response:

this should be the 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 are useless, this is a shorter 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;
    });
  }
  • Related