-
-
Notifications
You must be signed in to change notification settings - Fork 367
/
prefer-at.js
375 lines (320 loc) · 9.46 KB
/
prefer-at.js
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
'use strict';
const {isOpeningBracketToken, isClosingBracketToken, getStaticValue} = require('@eslint-community/eslint-utils');
const {
isParenthesized,
getParenthesizedRange,
getParenthesizedText,
isNodeMatchesNameOrPath,
needsSemicolon,
shouldAddParenthesesToMemberExpressionObject,
isLeftHandSide,
} = require('./utils/index.js');
const {
getNegativeIndexLengthNode,
removeLengthNode,
} = require('./shared/negative-index.js');
const {removeMemberExpressionProperty, removeMethodCall} = require('./fix/index.js');
const {isLiteral, isCallExpression, isMethodCall} = require('./ast/index.js');
const MESSAGE_ID_NEGATIVE_INDEX = 'negative-index';
const MESSAGE_ID_INDEX = 'index';
const MESSAGE_ID_STRING_CHAR_AT_NEGATIVE = 'string-char-at-negative';
const MESSAGE_ID_STRING_CHAR_AT = 'string-char-at';
const MESSAGE_ID_SLICE = 'slice';
const MESSAGE_ID_GET_LAST_FUNCTION = 'get-last-function';
const SUGGESTION_ID = 'use-at';
const messages = {
[MESSAGE_ID_NEGATIVE_INDEX]: 'Prefer `.at(…)` over `[….length - index]`.',
[MESSAGE_ID_INDEX]: 'Prefer `.at(…)` over index access.',
[MESSAGE_ID_STRING_CHAR_AT_NEGATIVE]: 'Prefer `String#at(…)` over `String#charAt(….length - index)`.',
[MESSAGE_ID_STRING_CHAR_AT]: 'Prefer `String#at(…)` over `String#charAt(…)`.',
[MESSAGE_ID_SLICE]: 'Prefer `.at(…)` over the first element from `.slice(…)`.',
[MESSAGE_ID_GET_LAST_FUNCTION]: 'Prefer `.at(-1)` over `{{description}}(…)` to get the last element.',
[SUGGESTION_ID]: 'Use `.at(…)`.',
};
const isArguments = node => node.type === 'Identifier' && node.name === 'arguments';
const isLiteralNegativeInteger = node =>
node.type === 'UnaryExpression'
&& node.prefix
&& node.operator === '-'
&& node.argument.type === 'Literal'
&& Number.isInteger(node.argument.value)
&& node.argument.value > 0;
const isZeroIndexAccess = node => {
const {parent} = node;
return parent.type === 'MemberExpression'
&& !parent.optional
&& parent.computed
&& parent.object === node
&& isLiteral(parent.property, 0);
};
const isArrayPopOrShiftCall = (node, method) => {
const {parent} = node;
return parent.type === 'MemberExpression'
&& !parent.optional
&& !parent.computed
&& parent.object === node
&& parent.property.type === 'Identifier'
&& parent.property.name === method
&& parent.parent.type === 'CallExpression'
&& parent.parent.callee === parent
&& !parent.parent.optional
&& parent.parent.arguments.length === 0;
};
const isArrayPopCall = node => isArrayPopOrShiftCall(node, 'pop');
const isArrayShiftCall = node => isArrayPopOrShiftCall(node, 'shift');
function checkSliceCall(node) {
const sliceArgumentsLength = node.arguments.length;
const [startIndexNode, endIndexNode] = node.arguments;
if (!isLiteralNegativeInteger(startIndexNode)) {
return;
}
let firstElementGetMethod = '';
if (isZeroIndexAccess(node)) {
if (isLeftHandSide(node.parent)) {
return;
}
firstElementGetMethod = 'zero-index';
} else if (isArrayShiftCall(node)) {
firstElementGetMethod = 'shift';
} else if (isArrayPopCall(node)) {
firstElementGetMethod = 'pop';
}
if (!firstElementGetMethod) {
return;
}
const startIndex = -startIndexNode.argument.value;
if (sliceArgumentsLength === 1) {
if (
firstElementGetMethod === 'zero-index'
|| firstElementGetMethod === 'shift'
|| (startIndex === -1 && firstElementGetMethod === 'pop')
) {
return {safeToFix: true, firstElementGetMethod};
}
return;
}
if (
isLiteralNegativeInteger(endIndexNode)
&& -endIndexNode.argument.value === startIndex + 1
) {
return {safeToFix: true, firstElementGetMethod};
}
if (firstElementGetMethod === 'pop') {
return;
}
return {safeToFix: false, firstElementGetMethod};
}
const lodashLastFunctions = [
'_.last',
'lodash.last',
'underscore.last',
];
/** @param {import('eslint').Rule.RuleContext} context */
function create(context) {
const {
getLastElementFunctions,
checkAllIndexAccess,
} = {
getLastElementFunctions: [],
checkAllIndexAccess: false,
...context.options[0],
};
const getLastFunctions = [...getLastElementFunctions, ...lodashLastFunctions];
const {sourceCode} = context;
// Index access
context.on('MemberExpression', node => {
if (
node.optional
|| !node.computed
|| isLeftHandSide(node)
) {
return;
}
const indexNode = node.property;
const lengthNode = getNegativeIndexLengthNode(indexNode, node.object);
if (!lengthNode) {
if (!checkAllIndexAccess) {
return;
}
// Only if we are sure it's an positive integer
const staticValue = getStaticValue(indexNode, sourceCode.getScope(indexNode));
if (!staticValue || !Number.isInteger(staticValue.value) || staticValue.value < 0) {
return;
}
}
const problem = {
node: indexNode,
messageId: lengthNode ? MESSAGE_ID_NEGATIVE_INDEX : MESSAGE_ID_INDEX,
};
if (isArguments(node.object)) {
return problem;
}
problem.fix = function * (fixer) {
if (lengthNode) {
yield removeLengthNode(lengthNode, fixer, sourceCode);
}
// Only remove space for `foo[foo.length - 1]`
if (
indexNode.type === 'BinaryExpression'
&& indexNode.operator === '-'
&& indexNode.left === lengthNode
&& indexNode.right.type === 'Literal'
&& /^\d+$/.test(indexNode.right.raw)
) {
const numberNode = indexNode.right;
const tokenBefore = sourceCode.getTokenBefore(numberNode);
if (
tokenBefore.type === 'Punctuator'
&& tokenBefore.value === '-'
&& /^\s+$/.test(sourceCode.text.slice(tokenBefore.range[1], numberNode.range[0]))
) {
yield fixer.removeRange([tokenBefore.range[1], numberNode.range[0]]);
}
}
const openingBracketToken = sourceCode.getTokenBefore(indexNode, isOpeningBracketToken);
yield fixer.replaceText(openingBracketToken, '.at(');
const closingBracketToken = sourceCode.getTokenAfter(indexNode, isClosingBracketToken);
yield fixer.replaceText(closingBracketToken, ')');
};
return problem;
});
// `string.charAt`
context.on('CallExpression', node => {
if (!isMethodCall(node, {
method: 'charAt',
argumentsLength: 1,
optionalCall: false,
optionalMember: false,
})) {
return;
}
const [indexNode] = node.arguments;
const lengthNode = getNegativeIndexLengthNode(indexNode, node.callee.object);
// `String#charAt` don't care about index value, we assume it's always number
if (!lengthNode && !checkAllIndexAccess) {
return;
}
return {
node: indexNode,
messageId: lengthNode ? MESSAGE_ID_STRING_CHAR_AT_NEGATIVE : MESSAGE_ID_STRING_CHAR_AT,
suggest: [{
messageId: SUGGESTION_ID,
* fix(fixer) {
if (lengthNode) {
yield removeLengthNode(lengthNode, fixer, sourceCode);
}
yield fixer.replaceText(node.callee.property, 'at');
},
}],
};
});
// `.slice()`
context.on('CallExpression', sliceCall => {
if (!isMethodCall(sliceCall, {
method: 'slice',
minimumArguments: 1,
maximumArguments: 2,
optionalCall: false,
optionalMember: false,
})) {
return;
}
const result = checkSliceCall(sliceCall);
if (!result) {
return;
}
const {safeToFix, firstElementGetMethod} = result;
/** @param {import('eslint').Rule.RuleFixer} fixer */
function * fix(fixer) {
// `.slice` to `.at`
yield fixer.replaceText(sliceCall.callee.property, 'at');
// Remove extra arguments
if (sliceCall.arguments.length !== 1) {
const [, start] = getParenthesizedRange(sliceCall.arguments[0], sourceCode);
const [end] = sourceCode.getLastToken(sliceCall).range;
yield fixer.removeRange([start, end]);
}
// Remove `[0]`, `.shift()`, or `.pop()`
if (firstElementGetMethod === 'zero-index') {
yield removeMemberExpressionProperty(fixer, sliceCall.parent, sourceCode);
} else {
yield * removeMethodCall(fixer, sliceCall.parent.parent, sourceCode);
}
}
const problem = {
node: sliceCall.callee.property,
messageId: MESSAGE_ID_SLICE,
};
if (safeToFix) {
problem.fix = fix;
} else {
problem.suggest = [{messageId: SUGGESTION_ID, fix}];
}
return problem;
});
context.on('CallExpression', node => {
if (!isCallExpression(node, {argumentsLength: 1, optional: false})) {
return;
}
const matchedFunction = getLastFunctions.find(nameOrPath => isNodeMatchesNameOrPath(node.callee, nameOrPath));
if (!matchedFunction) {
return;
}
const problem = {
node: node.callee,
messageId: MESSAGE_ID_GET_LAST_FUNCTION,
data: {description: matchedFunction.trim()},
};
const [array] = node.arguments;
if (isArguments(array)) {
return problem;
}
problem.fix = function (fixer) {
let fixed = getParenthesizedText(array, sourceCode);
if (
!isParenthesized(array, sourceCode)
&& shouldAddParenthesesToMemberExpressionObject(array, sourceCode)
) {
fixed = `(${fixed})`;
}
fixed = `${fixed}.at(-1)`;
const tokenBefore = sourceCode.getTokenBefore(node);
if (needsSemicolon(tokenBefore, sourceCode, fixed)) {
fixed = `;${fixed}`;
}
return fixer.replaceText(node, fixed);
};
return problem;
});
}
const schema = [
{
type: 'object',
additionalProperties: false,
properties: {
getLastElementFunctions: {
type: 'array',
uniqueItems: true,
},
checkAllIndexAccess: {
type: 'boolean',
default: false,
},
},
},
];
/** @type {import('eslint').Rule.RuleModule} */
module.exports = {
create,
meta: {
type: 'suggestion',
docs: {
description: 'Prefer `.at()` method for index access and `String#charAt()`.',
recommended: true,
},
fixable: 'code',
hasSuggestions: true,
schema,
messages,
},
};