-
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathprefer-static-collator.ts
More file actions
72 lines (67 loc) · 2.14 KB
/
prefer-static-collator.ts
File metadata and controls
72 lines (67 loc) · 2.14 KB
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
import type {Rule} from 'eslint';
import type {
CallExpression,
ArrowFunctionExpression,
FunctionExpression,
Node
} from 'estree';
const COMPARATOR_METHODS = new Set(['sort', 'toSorted']);
type FunctionExpr = (ArrowFunctionExpression | FunctionExpression) &
Rule.NodeParentExtension;
function findEnclosingCallback(node: Rule.Node): FunctionExpr | null {
let cur: Rule.Node | null | undefined = node.parent;
while (cur) {
if (
cur.type === 'ArrowFunctionExpression' ||
cur.type === 'FunctionExpression'
) {
return cur;
}
if (cur.type === 'FunctionDeclaration') {
return null;
}
cur = cur.parent;
}
return null;
}
function isComparatorCallback(fn: FunctionExpr): boolean {
const parent = fn.parent;
if (!parent || parent.type !== 'CallExpression') return false;
const callee = parent.callee;
if (callee.type !== 'MemberExpression' || callee.computed) return false;
if (callee.property.type !== 'Identifier') return false;
if (!COMPARATOR_METHODS.has(callee.property.name)) return false;
return (parent.arguments as Node[]).includes(fn);
}
export const preferStaticCollator: Rule.RuleModule = {
meta: {
type: 'suggestion',
docs: {
description:
'Prefer hoisting an `Intl.Collator` instance over calling localeCompare in a sort callback',
recommended: false
},
schema: [],
messages: {
preferStaticCollator:
'`localeCompare` constructs an `Intl.Collator` on every call. Hoist `const collator = new Intl.Collator(...)` outside the callback and use `collator.compare(a, b)`.'
}
},
create(context) {
return {
CallExpression(node: CallExpression & Rule.NodeParentExtension) {
if (node.callee.type !== 'MemberExpression') return;
if (node.callee.computed) return;
if (
node.callee.property.type !== 'Identifier' ||
node.callee.property.name !== 'localeCompare'
)
return;
const fn = findEnclosingCallback(node);
if (!fn) return;
if (!isComparatorCallback(fn)) return;
context.report({node, messageId: 'preferStaticCollator'});
}
};
}
};