-
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathprefer-array-to-spliced.ts
More file actions
68 lines (63 loc) · 1.77 KB
/
prefer-array-to-spliced.ts
File metadata and controls
68 lines (63 loc) · 1.77 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
import type {Rule} from 'eslint';
import type {CallExpression} from 'estree';
import {
getArrayFromCopyPattern,
formatArguments,
needsParensForPropertyAccess,
isCopyPatternOptional
} from '../utils/ast.js';
export const preferArrayToSpliced: Rule.RuleModule = {
meta: {
type: 'suggestion',
docs: {
description:
'Prefer Array.prototype.toSpliced() over copying and splicing arrays',
recommended: true
},
fixable: 'code',
schema: [],
messages: {
preferToSpliced:
'Use {{array}}.toSpliced() instead of copying and splicing'
}
},
create(context) {
const sourceCode = context.sourceCode;
return {
CallExpression(node: CallExpression) {
if (
node.callee.type !== 'MemberExpression' ||
node.callee.property.type !== 'Identifier' ||
node.callee.property.name !== 'splice'
) {
return;
}
const spliceCallee = node.callee.object;
const arrayNode = getArrayFromCopyPattern(spliceCallee);
if (arrayNode) {
const rawText = sourceCode.getText(arrayNode);
const arrayText = needsParensForPropertyAccess(arrayNode)
? `(${rawText})`
: rawText;
const argsText = formatArguments(node.arguments, sourceCode);
const optionalChain = isCopyPatternOptional(spliceCallee)
? '?.'
: '.';
context.report({
node,
messageId: 'preferToSpliced',
data: {
array: rawText
},
fix(fixer) {
return fixer.replaceText(
node,
`${arrayText}${optionalChain}toSpliced(${argsText})`
);
}
});
}
}
};
}
};