javascript - 如何避免重复命令两次
问题描述
我有一个按值对 JS 对象数组进行排序的函数。该函数需要一个用于进行排序的键。一旦它具有所有值,该函数以 asc 或 desc 顺序对结果进行排序,这就是我使用重复代码的地方。唯一的区别是 ">、<" 符号。
这是代码......,我怎样才能重写它以保持干净而不重复代码?
重复命令: results[0].sort( (a, b) => ( a[ this.orderBy ] > b[ this.orderBy ] ) ? 1 : -1 )
if( this.orderBy ) {
results = this.order === 'asc' ?
results[0].sort( (a, b) => (
a[ this.orderBy ] > b[ this.orderBy ] ) ? 1 : -1 ):
results[0].sort( (a, b) => (
a[ this.orderBy ] < b[ this.orderBy ] ) ? 1 : -1 );
}
解决方案
这是一种方法:
const inversionFactor = this.order === 'asc' ? 1 : -1;
results = results[0].sort( (a, b) =>
a[ this.orderBy ] < b[ this.orderBy ] : -1 * inversionFactor : 1 * inversionFactor
);
编辑: 您当前的方法存在一个问题,即您没有考虑两个值相等的情况。这是一种考虑到这一点并避免重复的方法。
// this is a reusable function and can go outside of other functions
const compareBy = (prop, invert) => (a, b) => {
if (a[prop] === b[prop]) { return 0; }
return (a[prop] < b[prop] ? -1 : 1) * (invert ? -1 : 1);
};
results = results[0].sort(compareBy(this.orderBy, this.order === 'desc'));
推荐阅读
- laravel - 如何在以 Vue 作为前端的 Laravel 项目中使用 Typescript?
- c# - 鼠标滚轮事件未在第二个监视器中引发
- android - 将多个数据从 Android SQLLite 同步到 MariaDB
- css - 相同的背景颜色,不同的渐变宽度
- regex - 如何验证字符在输入字符串中出现的次数?
- android - 为什么我在“zxing”应用“Kotlin”上启动“OnPause”后我的应用退出
- javascript - Vue js "this" 被 image.onload "this" 覆盖
- mysql - 使用基于 Avg 的 Max 和 Min 来确定最低平均成本和最高平均成本时出错(MySQL)
- wpf - WFP dxg datagrid,自动选择第一行并获得焦点
- c++ - 带空格的 system() 命令