如何避免命令重复两次



我有一个函数,按值对JS对象数组进行排序。该函数接受一个键,它使用这个键进行排序。一旦它有了所有的值,函数将结果按asc或desc顺序排序,这就是我使用重复代码的地方。唯一的区别是"> <&quot;迹象。

下面是代码…我如何重写这是移动干净,不重复的代码?

重复命令:结果[0]。Sort ((a, b) =>a[这个]命令]>b这。(命令)?(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'));

最新更新