/
prefer-find.ts
344 lines (310 loc) · 11 KB
/
prefer-find.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
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
import type { TSESLint, TSESTree } from '@typescript-eslint/utils';
import { AST_NODE_TYPES } from '@typescript-eslint/utils';
import type { RuleFix, Scope } from '@typescript-eslint/utils/ts-eslint';
import * as tsutils from 'ts-api-utils';
import type { Type } from 'typescript';
import {
createRule,
getConstrainedTypeAtLocation,
getParserServices,
getStaticValue,
nullThrows,
} from '../util';
export default createRule({
name: 'prefer-find',
meta: {
docs: {
description:
'Enforce the use of Array.prototype.find() over Array.prototype.filter() followed by [0] when looking for a single result',
requiresTypeChecking: true,
},
messages: {
preferFind: 'Prefer .find(...) instead of .filter(...)[0].',
preferFindSuggestion: 'Use .find(...) instead of .filter(...)[0].',
},
schema: [],
type: 'suggestion',
hasSuggestions: true,
},
defaultOptions: [],
create(context) {
const globalScope = context.sourceCode.getScope(context.sourceCode.ast);
const services = getParserServices(context);
const checker = services.program.getTypeChecker();
interface FilterExpressionData {
isBracketSyntaxForFilter: boolean;
filterNode: TSESTree.Node;
}
function parseArrayFilterExpressions(
expression: TSESTree.Expression,
): FilterExpressionData[] {
if (expression.type === AST_NODE_TYPES.SequenceExpression) {
// Only the last expression in (a, b, [1, 2, 3].filter(condition))[0] matters
const lastExpression = nullThrows(
expression.expressions.at(-1),
'Expected to have more than zero expressions in a sequence expression',
);
return parseArrayFilterExpressions(lastExpression);
}
if (expression.type === AST_NODE_TYPES.ChainExpression) {
return parseArrayFilterExpressions(expression.expression);
}
// This is the only reason we're returning a list rather than a single value.
if (expression.type === AST_NODE_TYPES.ConditionalExpression) {
// Both branches of the ternary _must_ return results.
const consequentResult = parseArrayFilterExpressions(
expression.consequent,
);
if (consequentResult.length === 0) {
return [];
}
const alternateResult = parseArrayFilterExpressions(
expression.alternate,
);
if (alternateResult.length === 0) {
return [];
}
// Accumulate the results from both sides and pass up the chain.
return [...consequentResult, ...alternateResult];
}
// Check if it looks like <<stuff>>(...), but not <<stuff>>?.(...)
if (
expression.type === AST_NODE_TYPES.CallExpression &&
!expression.optional
) {
const callee = expression.callee;
// Check if it looks like <<stuff>>.filter(...) or <<stuff>>['filter'](...),
// or the optional chaining variants.
if (callee.type === AST_NODE_TYPES.MemberExpression) {
const isBracketSyntaxForFilter = callee.computed;
if (isStaticMemberAccessOfValue(callee, 'filter', globalScope)) {
const filterNode = callee.property;
const filteredObjectType = getConstrainedTypeAtLocation(
services,
callee.object,
);
// As long as the object is a (possibly nullable) array,
// this is an Array.prototype.filter expression.
if (isArrayish(filteredObjectType)) {
return [
{
isBracketSyntaxForFilter,
filterNode,
},
];
}
}
}
}
// not a filter expression.
return [];
}
/**
* Tells whether the type is a possibly nullable array/tuple or union thereof.
*/
function isArrayish(type: Type): boolean {
let isAtLeastOneArrayishComponent = false;
for (const unionPart of tsutils.unionTypeParts(type)) {
if (
tsutils.isIntrinsicNullType(unionPart) ||
tsutils.isIntrinsicUndefinedType(unionPart)
) {
continue;
}
// apparently checker.isArrayType(T[] & S[]) => false.
// so we need to check the intersection parts individually.
const isArrayOrIntersectionThereof = tsutils
.intersectionTypeParts(unionPart)
.every(
intersectionPart =>
checker.isArrayType(intersectionPart) ||
checker.isTupleType(intersectionPart),
);
if (!isArrayOrIntersectionThereof) {
// There is a non-array, non-nullish type component,
// so it's not an array.
return false;
}
isAtLeastOneArrayishComponent = true;
}
return isAtLeastOneArrayishComponent;
}
function getObjectIfArrayAtZeroExpression(
node: TSESTree.CallExpression,
): TSESTree.Expression | undefined {
// .at() should take exactly one argument.
if (node.arguments.length !== 1) {
return undefined;
}
const callee = node.callee;
if (
callee.type === AST_NODE_TYPES.MemberExpression &&
!callee.optional &&
isStaticMemberAccessOfValue(callee, 'at', globalScope)
) {
const atArgument = getStaticValue(node.arguments[0], globalScope);
if (atArgument != null && isTreatedAsZeroByArrayAt(atArgument.value)) {
return callee.object;
}
}
return undefined;
}
/**
* Implements the algorithm for array indexing by `.at()` method.
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at#parameters
*/
function isTreatedAsZeroByArrayAt(value: unknown): boolean {
// This would cause the number constructor coercion to throw. Other static
// values are safe.
if (typeof value === 'symbol') {
return false;
}
const asNumber = Number(value);
if (isNaN(asNumber)) {
return true;
}
return Math.trunc(asNumber) === 0;
}
function isMemberAccessOfZero(
node: TSESTree.MemberExpressionComputedName,
): boolean {
const property = getStaticValue(node.property, globalScope);
// Check if it looks like <<stuff>>[0] or <<stuff>>['0'], but not <<stuff>>?.[0]
return (
!node.optional &&
property != null &&
isTreatedAsZeroByMemberAccess(property.value)
);
}
/**
* Implements the algorithm for array indexing by member operator.
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#array_indices
*/
function isTreatedAsZeroByMemberAccess(value: unknown): boolean {
return String(value) === '0';
}
function generateFixToRemoveArrayElementAccess(
fixer: TSESLint.RuleFixer,
arrayNode: TSESTree.Expression,
wholeExpressionBeingFlagged: TSESTree.Expression,
): RuleFix {
const tokenToStartDeletingFrom = nullThrows(
// The next `.` or `[` is what we're looking for.
// think of (...).at(0) or (...)[0] or even (...)["at"](0).
context.sourceCode.getTokenAfter(
arrayNode,
token => token.value === '.' || token.value === '[',
),
'Expected to find a member access token!',
);
return fixer.removeRange([
tokenToStartDeletingFrom.range[0],
wholeExpressionBeingFlagged.range[1],
]);
}
function generateFixToReplaceFilterWithFind(
fixer: TSESLint.RuleFixer,
filterExpression: FilterExpressionData,
): TSESLint.RuleFix {
return fixer.replaceText(
filterExpression.filterNode,
filterExpression.isBracketSyntaxForFilter ? '"find"' : 'find',
);
}
return {
// This query will be used to find things like `filteredResults.at(0)`.
CallExpression(node): void {
const object = getObjectIfArrayAtZeroExpression(node);
if (object) {
const filterExpressions = parseArrayFilterExpressions(object);
if (filterExpressions.length !== 0) {
context.report({
node,
messageId: 'preferFind',
suggest: [
{
messageId: 'preferFindSuggestion',
fix: (fixer): TSESLint.RuleFix[] => {
return [
...filterExpressions.map(filterExpression =>
generateFixToReplaceFilterWithFind(
fixer,
filterExpression,
),
),
// Get rid of the .at(0) or ['at'](0).
generateFixToRemoveArrayElementAccess(
fixer,
object,
node,
),
];
},
},
],
});
}
}
},
// This query will be used to find things like `filteredResults[0]`.
//
// Note: we're always looking for array member access to be "computed",
// i.e. `filteredResults[0]`, since `filteredResults.0` isn't a thing.
['MemberExpression[computed=true]'](
node: TSESTree.MemberExpressionComputedName,
): void {
if (isMemberAccessOfZero(node)) {
const object = node.object;
const filterExpressions = parseArrayFilterExpressions(object);
if (filterExpressions.length !== 0) {
context.report({
node,
messageId: 'preferFind',
suggest: [
{
messageId: 'preferFindSuggestion',
fix: (fixer): TSESLint.RuleFix[] => {
return [
...filterExpressions.map(filterExpression =>
generateFixToReplaceFilterWithFind(
fixer,
filterExpression,
),
),
// Get rid of the [0].
generateFixToRemoveArrayElementAccess(
fixer,
object,
node,
),
];
},
},
],
});
}
}
},
};
},
});
/**
* Answers whether the member expression looks like
* `x.memberName`, `x['memberName']`,
* or even `const mn = 'memberName'; x[mn]` (or optional variants thereof).
*/
function isStaticMemberAccessOfValue(
memberExpression:
| TSESTree.MemberExpressionComputedName
| TSESTree.MemberExpressionNonComputedName,
value: string,
scope?: Scope.Scope | undefined,
): boolean {
if (!memberExpression.computed) {
// x.memberName case.
return memberExpression.property.name === value;
}
// x['memberName'] cases.
const staticValueResult = getStaticValue(memberExpression.property, scope);
return staticValueResult != null && value === staticValueResult.value;
}