Skip to content

Rule Proposal: require-array-sort-compare #247

Closed
@mysticatea

Description

@mysticatea

Please describe what the rule should do:

From eslint/eslint#10363

This rule reports xs.sort() calls with no arguments if xs is an array.

let xs: any[]

//✘ BAD
xs.sort()

//✔ GOOD
xs.sort((a, b) => a - b)
xs.sort((a, b) => a.localeCompare(b))
xs.sort(cmp)
xs.sort(undefined) //← explicit default behavior

Because the default compare function does compare the array elements as strings then it can cause unexpected behavior. For example:

[1, 2, 10].sort() //→ it becomes [1, 10, 2]

The language spec describes this matter.

NOTE 2: Method 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.
https://www.ecma-international.org/ecma-262/8.0/#sec-sortcompare

Because the rule doesn't want to warn the sort() method of non-array class, I think that this rule fits to this plugin.

What category of rule is this? (place an "X" next to just one item)

[ ] Enforces code style
[X] Warns about a potential error
[ ] Suggests an alternate way of doing something
[ ] Other (please specify:)

Provide 2-3 code examples that this rule will warn about:

let xs: any[]
let ys: ReadonlyArray<any>
let zs: { sort(): void }

//✘ BAD
xs.sort()
ys.sort()

//✔ GOOD
xs.sort((a, b) => a - b)
ys.sort((a, b) => a - b)
zs.sort() //← this is not an array.

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions