UNPKG

2.46 kBMarkdownView Raw
1# `require-array-sort-compare`
2
3Requires `Array#sort` calls to always provide a `compareFunction`.
4
5This rule prevents invoking the `Array#sort()` method without providing a `compare` argument.
6
7When called without a compare function, `Array#sort()` converts all non-undefined array elements into strings and then compares said strings based off their UTF-16 code units.
8
9The result is that elements are sorted alphabetically, regardless of their type.
10When sorting numbers, this results in the classic "10 before 2" order:
11
12```ts
13[1, 2, 3, 10, 20, 30].sort(); //→ [1, 10, 2, 20, 3, 30]
14```
15
16This also means that `Array#sort` does not always sort consistently, as elements may have custom `#toString` implementations that are not deterministic; this trap is noted in the language specification thusly:
17
18:::note
19Method calls performed by the `ToString` abstract operations in steps 5 and 7 have the potential to cause `SortCompare` to not behave as a consistent comparison function.
20
21https://www.ecma-international.org/ecma-262/9.0/#sec-sortcompare
22:::
23
24## Rule Details
25
26This rule aims to ensure all calls of the native `Array#sort` method provide a `compareFunction`, while ignoring calls to user-defined `sort` methods.
27
28Examples of code for this rule:
29
30<!--tabs-->
31
32### ❌ Incorrect
33
34```ts
35const array: any[];
36const stringArray: string[];
37
38array.sort();
39
40// String arrays should be sorted using `String#localeCompare`.
41stringArray.sort();
42```
43
44### ✅ Correct
45
46```ts
47const array: any[];
48const userDefinedType: { sort(): void };
49
50array.sort((a, b) => a - b);
51array.sort((a, b) => a.localeCompare(b));
52
53userDefinedType.sort();
54```
55
56## Options
57
58The rule accepts an options object with the following properties:
59
60```ts
61type Options = {
62 /**
63 * If true, an array which all elements are string is ignored.
64 */
65 ignoreStringArrays?: boolean;
66};
67
68const defaults = {
69 ignoreStringArrays: false,
70};
71```
72
73### `ignoreStringArrays`
74
75Examples of code for this rule with `{ ignoreStringArrays: true }`:
76
77<!--tabs-->
78
79#### ❌ Incorrect
80
81```ts
82const one = 1;
83const two = 2;
84const three = 3;
85[one, two, three].sort();
86```
87
88#### ✅ Correct
89
90```ts
91const one = '1';
92const two = '2';
93const three = '3';
94[one, two, three].sort();
95```
96
97## When Not To Use It
98
99If you understand the language specification enough, you can turn this rule off safely.
100
101## Attributes
102
103- Configs:
104 - [ ] ✅ Recommended
105 - [ ] 🔒 Strict
106- [ ] 🔧 Fixable
107- [x] 💭 Requires type information