-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
require-array-sort-compare.ts
91 lines (80 loc) · 2.35 KB
/
require-array-sort-compare.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import type { TSESTree } from '@typescript-eslint/utils';
import {
createRule,
getConstrainedTypeAtLocation,
getParserServices,
getTypeName,
isTypeArrayTypeOrUnionOfArrayTypes,
} from '../util';
export type Options = [
{
ignoreStringArrays?: boolean;
},
];
export type MessageIds = 'requireCompare';
export default createRule<Options, MessageIds>({
name: 'require-array-sort-compare',
defaultOptions: [
{
ignoreStringArrays: true,
},
],
meta: {
type: 'problem',
docs: {
description:
'Require `Array#sort` and `Array#toSorted` calls to always provide a `compareFunction`',
requiresTypeChecking: true,
},
messages: {
requireCompare: "Require 'compare' argument.",
},
schema: [
{
type: 'object',
additionalProperties: false,
properties: {
ignoreStringArrays: {
description:
'Whether to ignore arrays in which all elements are strings.',
type: 'boolean',
},
},
},
],
},
create(context, [options]) {
const services = getParserServices(context);
const checker = services.program.getTypeChecker();
/**
* Check if a given node is an array which all elements are string.
* @param node
*/
function isStringArrayNode(node: TSESTree.Expression): boolean {
const type = services.getTypeAtLocation(node);
if (checker.isArrayType(type) || checker.isTupleType(type)) {
const typeArgs = checker.getTypeArguments(type);
return typeArgs.every(arg => getTypeName(checker, arg) === 'string');
}
return false;
}
function checkSortArgument(callee: TSESTree.MemberExpression): void {
const calleeObjType = getConstrainedTypeAtLocation(
services,
callee.object,
);
if (options.ignoreStringArrays && isStringArrayNode(callee.object)) {
return;
}
if (isTypeArrayTypeOrUnionOfArrayTypes(calleeObjType, checker)) {
context.report({ node: callee.parent, messageId: 'requireCompare' });
}
}
return {
"CallExpression[arguments.length=0] > MemberExpression[property.name='sort'][computed=false]":
checkSortArgument,
"CallExpression[arguments.length=0] > MemberExpression[property.name='toSorted'][computed=false]":
checkSortArgument,
};
},
});