将这个嵌套的三元操作提取为一个独立的语句。Sonar问题

huangapple go评论70阅读模式
英文:

Extract this nested ternary operation into an independent statement. 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));
}
英文:

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

答案1

得分: 0

这应该是解决方案:

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;
      }
    }
  });
}

一些else是多余的,这是更简短的形式:

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;
  });
}
英文:

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;
    });
  }

huangapple
  • 本文由 发表于 2023年1月9日 14:23:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/75053786.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定