-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
require-array-sort-compare.ts
84 lines (74 loc) · 2.13 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
import type { TSESTree } from '@typescript-eslint/utils';
import * as util from '../util';
export type Options = [
{
ignoreStringArrays?: boolean;
},
];
export type MessageIds = 'requireCompare';
export default util.createRule<Options, MessageIds>({
name: 'require-array-sort-compare',
defaultOptions: [
{
ignoreStringArrays: false,
},
],
meta: {
type: 'problem',
docs: {
description:
'Require `Array#sort` 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 = util.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 = util.getTypeArguments(type, checker);
return typeArgs.every(
arg => util.getTypeName(checker, arg) === 'string',
);
}
return false;
}
return {
"CallExpression[arguments.length=0] > MemberExpression[property.name='sort'][computed=false]"(
callee: TSESTree.MemberExpression,
): void {
const calleeObjType = util.getConstrainedTypeAtLocation(
services,
callee.object,
);
if (options.ignoreStringArrays && isStringArrayNode(callee.object)) {
return;
}
if (util.isTypeArrayTypeOrUnionOfArrayTypes(calleeObjType, checker)) {
context.report({ node: callee.parent, messageId: 'requireCompare' });
}
},
};
},
});