/
require-array-sort-compare.ts
53 lines (48 loc) · 1.63 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
import { TSESTree } from '@typescript-eslint/experimental-utils';
import ts from 'typescript';
import * as util from '../util';
export default util.createRule({
name: 'require-array-sort-compare',
defaultOptions: [],
meta: {
type: 'problem',
docs: {
description: 'Enforce giving `compare` argument to `Array#sort`',
category: 'Best Practices',
recommended: false,
requiresTypeChecking: true,
},
messages: {
requireCompare: "Require 'compare' argument.",
},
schema: [],
},
create(context) {
const service = util.getParserServices(context);
const checker = service.program.getTypeChecker();
return {
":matches(CallExpression, OptionalCallExpression)[arguments.length=0] > :matches(MemberExpression, OptionalMemberExpression)[property.name='sort'][computed=false]"(
node: TSESTree.MemberExpression | TSESTree.OptionalMemberExpression,
): void {
// Get the symbol of the `sort` method.
const tsNode = service.esTreeNodeToTSNodeMap.get(node);
const sortSymbol = checker.getSymbolAtLocation(tsNode);
if (sortSymbol == null) {
return;
}
// Check the owner type of the `sort` method.
for (const methodDecl of sortSymbol.declarations) {
const typeDecl = methodDecl.parent;
if (
ts.isInterfaceDeclaration(typeDecl) &&
ts.isSourceFile(typeDecl.parent) &&
typeDecl.name.escapedText === 'Array'
) {
context.report({ node: node.parent!, messageId: 'requireCompare' });
return;
}
}
},
};
},
});