forked from e18e/eslint-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprefer-array-from-map.ts
More file actions
77 lines (68 loc) · 2.09 KB
/
Copy pathprefer-array-from-map.ts
File metadata and controls
77 lines (68 loc) · 2.09 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
import type {Rule} from 'eslint';
import type {CallExpression} from 'estree';
export const preferArrayFromMap: Rule.RuleModule = {
meta: {
type: 'suggestion',
docs: {
description:
'Prefer Array.from(iterable, mapper) over [...iterable].map(mapper) to avoid intermediate array allocation',
recommended: true
},
fixable: 'code',
schema: [],
messages: {
preferArrayFrom:
'Use Array.from({{iterable}}, {{mapper}}) instead of [...{{iterable}}].map({{mapper}}) to avoid creating an intermediate array'
}
},
create(context) {
const sourceCode = context.sourceCode;
return {
CallExpression(node: CallExpression) {
// Check if this is a .map() call
if (node.callee.type !== 'MemberExpression') {
return;
}
if (
node.callee.property.type !== 'Identifier' ||
node.callee.property.name !== 'map'
) {
return;
}
// Check if .map() is being called on an array literal with spread
if (node.callee.object.type !== 'ArrayExpression') {
return;
}
const arrayExpr = node.callee.object;
// Check if the array has exactly one element and it's a spread element
if (
arrayExpr.elements.length !== 1 ||
arrayExpr.elements[0]?.type !== 'SpreadElement'
) {
return;
}
// Check if map has exactly one argument (the mapper function)
if (node.arguments.length !== 1) {
return;
}
const spreadElement = arrayExpr.elements[0];
const iterableText = sourceCode.getText(spreadElement.argument);
const mapperText = sourceCode.getText(node.arguments[0]!);
context.report({
node,
messageId: 'preferArrayFrom',
data: {
iterable: iterableText,
mapper: mapperText
},
fix(fixer) {
return fixer.replaceText(
node,
`Array.from(${iterableText}, ${mapperText})`
);
}
});
}
};
}
};