Skip to content

useArraySortCompare

¥Summary

¥How to configure

biome.json
{
"linter": {
"rules": {
"nursery": {
"useArraySortCompare": "error"
}
}
}
}

¥Description

要求 Array#sort 和 Array#toSorted 调用始终提供 compareFunction。

¥Require Array#sort and Array#toSorted calls to always provide a compareFunction.

当未使用比较函数调用 Array#sort()Array#toSorted() 时,它们会将所有非 undefined 数组元素转换为字符串,然后基于它们的 UTF-16 代码单元 ECMA 规范 对这些字符串进行比较。

¥When called without a compare function, Array#sort() and Array#toSorted() converts all non-undefined array elements into strings and then compares said strings based off their UTF-16 code units ECMA specification.

结果是元素按字母顺序排序,无论其类型如何。例如,对数字进行排序时,会得到 “10 之前 2” 顺序:

¥The result is that elements are sorted alphabetically, regardless of their type. For example, when sorting numbers, this results in a “10 before 2” order:

example.ts
[1, 2, 3, 10, 20, 30].sort(); //→ [1, 10, 2, 20, 3, 30]

此规则会报告任何未提供比较参数的排序方法调用。

¥This rule reports on any call to the sort methods that do not provide a compare argument.

¥Examples

¥Invalid

invalid.ts
const array: any[] = [];
array.sort();
/invalid.ts:2:1 lint/nursery/useArraySortCompare ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Compare function missing.

1 │ const array: any[] = [];
> 2 │ array.sort();
^^^^^^^^^^^^
3 │

When called without a compare function, Array#sort() and Array#toSorted() converts all non-undefined array elements into strings and then compares said strings based off their UTF-16 code units.

Add a compare function to prevent unexpected sorting.

¥Valid

valid.ts
const array: any[] = [];
array.sort((a, b) => a - b);

¥Related links