-
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathprefer-charcode-at-in-loop.ts
More file actions
206 lines (188 loc) · 5.49 KB
/
Copy pathprefer-charcode-at-in-loop.ts
File metadata and controls
206 lines (188 loc) · 5.49 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
import type {TSESLint, TSESTree} from '@typescript-eslint/utils';
import type ts from 'typescript';
import {needsParensForPropertyAccess} from '../utils/ast.js';
import {tryGetTypedParserServices} from '../utils/typescript.js';
type MessageIds = 'preferCharCodeAt' | 'replaceWithCharCodeAt';
const EQUALITY_OPERATORS = new Set(['===', '!==', '==', '!=']);
const LOOP_TYPES = new Set([
'ForStatement',
'ForInStatement',
'ForOfStatement',
'WhileStatement',
'DoWhileStatement'
]);
const FUNCTION_TYPES = new Set([
'FunctionDeclaration',
'FunctionExpression',
'ArrowFunctionExpression'
]);
function isSingleCharStringLiteral(
node: TSESTree.Node
): node is TSESTree.StringLiteral {
return (
node.type === 'Literal' &&
typeof node.value === 'string' &&
node.value.length === 1
);
}
function isComputedMember(
node: TSESTree.Node
): node is TSESTree.MemberExpression {
return node.type === 'MemberExpression' && node.computed && !node.optional;
}
function isStringLiteralExpression(node: TSESTree.Node): boolean {
return (
(node.type === 'Literal' && typeof node.value === 'string') ||
(node.type === 'TemplateLiteral' && node.expressions.length === 0)
);
}
function getTypeInfo(
node: TSESTree.Node,
context: Readonly<TSESLint.RuleContext<MessageIds, []>>
): {type: ts.Type; checker: ts.TypeChecker} | null {
const services = tryGetTypedParserServices(context);
if (!services) {
return null;
}
const type = services.getTypeAtLocation(node);
if (!type) {
return null;
}
return {type, checker: services.program.getTypeChecker()};
}
function isKnownStringExpression(
node: TSESTree.Node,
context: Readonly<TSESLint.RuleContext<MessageIds, []>>
): boolean {
if (isStringLiteralExpression(node)) {
return true;
}
const info = getTypeInfo(node, context);
if (!info) {
return false;
}
if (info.checker.typeToString(info.type) === 'any') {
return false;
}
return info.checker.isTypeAssignableTo(
info.type,
info.checker.getStringType()
);
}
function isUnsafeIndex(
property: TSESTree.Node,
context: Readonly<TSESLint.RuleContext<MessageIds, []>>
): boolean {
if (property.type === 'Literal') {
return typeof property.value === 'number'
? !Number.isInteger(property.value)
: true;
}
const info = getTypeInfo(property, context);
if (!info) {
return false;
}
return !info.checker.isTypeAssignableTo(
info.type,
info.checker.getNumberType()
);
}
function isInLoop(node: TSESTree.Node): boolean {
let current: TSESTree.Node | undefined = node.parent;
while (current) {
if (FUNCTION_TYPES.has(current.type)) {
return false;
}
if (LOOP_TYPES.has(current.type)) {
return true;
}
current = current.parent;
}
return false;
}
export const preferCharCodeAtInLoop: TSESLint.RuleModule<MessageIds, []> = {
meta: {
type: 'suggestion',
docs: {
description:
'Prefer `charCodeAt()` over indexed string access for single-character comparisons inside loops'
},
hasSuggestions: true,
schema: [],
messages: {
preferCharCodeAt:
'Comparing indexed string access to a single-character string can allocate and compare a one-character string. In a loop, charCodeAt() against a numeric code unit is faster.',
replaceWithCharCodeAt:
'Replace with charCodeAt() and code unit {{code}} for {{quoted}}.'
}
},
defaultOptions: [],
create(context) {
const sourceCode = context.sourceCode;
return {
BinaryExpression(node: TSESTree.BinaryExpression) {
if (!EQUALITY_OPERATORS.has(node.operator)) {
return;
}
let member: TSESTree.MemberExpression;
let charLiteral: TSESTree.StringLiteral;
let charOnRight: boolean;
if (
isComputedMember(node.left) &&
isSingleCharStringLiteral(node.right)
) {
member = node.left;
charLiteral = node.right;
charOnRight = true;
} else if (
isSingleCharStringLiteral(node.left) &&
isComputedMember(node.right)
) {
member = node.right;
charLiteral = node.left;
charOnRight = false;
} else {
return;
}
if (!isInLoop(node)) {
return;
}
if (isUnsafeIndex(member.property, context)) {
return;
}
if (!isKnownStringExpression(member.object, context)) {
return;
}
const rawObjectText = sourceCode.getText(member.object);
const objectText =
needsParensForPropertyAccess(member.object) ||
member.object.type === 'ChainExpression'
? `(${rawObjectText})`
: rawObjectText;
const indexText = sourceCode.getText(member.property);
const char = charLiteral.value;
const code = char.charCodeAt(0);
const charCodeAtCall = `${objectText}.charCodeAt(${indexText})`;
const replacement = charOnRight
? `${charCodeAtCall} ${node.operator} ${code}`
: `${code} ${node.operator} ${charCodeAtCall}`;
context.report({
node,
messageId: 'preferCharCodeAt',
suggest: [
{
messageId: 'replaceWithCharCodeAt',
data: {
code: String(code),
quoted: JSON.stringify(char)
},
fix(fixer) {
return fixer.replaceText(node, replacement);
}
}
]
});
}
};
}
};