英文:
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;
});
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论