sindresorhus/eslint-plugin-unicorn

Rule proposal: Enforce compare function style for `Array#sort()`

已關閉

#1,473 建立於 2021年8月8日

 (2 則留言) (3 個反應) (0 位負責人)JavaScript (468 個分叉)user submission
help wantednew rule

倉庫指標

星標
 (5,022 顆星)
PR 合併指標
 (平均合併 1天 16小時) (30 天內合併 399 個 PR)

描述

I've seen many people just write the compare function too complicated, yes sometimes maybe it's more readable, but sometimes it's just too long.

Fail

array.sort((a, b) => {
	if (a > b) {
		return 1;
	}

	if (a < b) {
		return -1;
	}

	return 0;
});
array.sort((a, b) => a > b ? 1 : -1);
array.sort((a, b) => {
	if (a.foo > b.foo) {
		return 1;
	}

	if (a.foo < b.foo) {
		return -1;
	}

	if (a.bar > b.bar) {
		return 1;
	}

	if (a.bar < b.bar) {
		return -1;
	}

	return 0;
});
array.sort(() => Math.random() > 0. 5 ? 1 : -1);

Pass

array.sort((a, b) => a - b);
array.sort((a, b) => a.localeCompare(b));
array.sort((a, b) => a.foo - b.foo || a.bar - b.bar);
array.sort(() => Math.random() - 0.5);

This rule should not fixable unless we are sure they are numbers.

貢獻者指南