-
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathprefer-array-at.ts
More file actions
95 lines (80 loc) · 2.24 KB
/
prefer-array-at.ts
File metadata and controls
95 lines (80 loc) · 2.24 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
import type {TSESLint, TSESTree} from '@typescript-eslint/utils';
import {isArrayType, isStringType} from '../utils/typescript.js';
type MessageIds = 'preferAt';
export const preferArrayAt: TSESLint.RuleModule<MessageIds, []> = {
meta: {
type: 'suggestion',
docs: {
description: 'Prefer Array.prototype.at() over length-based indexing'
},
fixable: 'code',
schema: [],
messages: {
preferAt: 'Use .at(-1) instead of [{{array}}.length - 1]'
}
},
defaultOptions: [],
create(context) {
const sourceCode = context.sourceCode;
return {
MemberExpression(node: TSESTree.MemberExpression) {
if (!node.computed || !node.property) {
return;
}
if (node.property.type !== 'BinaryExpression') {
return;
}
const propertyExpr = node.property;
if (propertyExpr.operator !== '-') {
return;
}
if (
propertyExpr.right.type !== 'Literal' ||
propertyExpr.right.value !== 1
) {
return;
}
if (propertyExpr.left.type !== 'MemberExpression') {
return;
}
const leftMember = propertyExpr.left;
if (
leftMember.property.type !== 'Identifier' ||
leftMember.property.name !== 'length'
) {
return;
}
const arrayText = sourceCode.getText(node.object);
const lengthArrayText = sourceCode.getText(leftMember.object);
if (arrayText !== lengthArrayText) {
return;
}
const parent = node.parent;
if (
parent &&
parent.type === 'AssignmentExpression' &&
parent.left === node
) {
return;
}
// Check if the object supports .at() (array or string, when types are available)
if (
isArrayType(node.object, context) === false &&
isStringType(node.object, context) === false
) {
return;
}
context.report({
node,
messageId: 'preferAt',
data: {
array: arrayText
},
fix(fixer) {
return fixer.replaceText(node, `${arrayText}.at(-1)`);
}
});
}
};
}
};