Repository navigation
Expand file tree
/
Copy pathprefer-array-from-map.ts
More file actions
94 lines (83 loc) · 2.57 KB
/
Copy pathprefer-array-from-map.ts
File metadata and controls
94 lines (83 loc) · 2.57 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
import type {Rule} from 'eslint';
import type {CallExpression} from 'estree';
import {formatArguments} from '../utils/ast.js';
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, fn)` instead of `[...iterable].map(fn)` 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 mapper = node.arguments[0]!;
// Array.from's mapper is called with (element, index) only, so a
// callback which can access the third `array` argument can't be
// converted
if (
mapper.type === 'FunctionExpression' ||
mapper.type === 'ArrowFunctionExpression'
) {
if (
mapper.params.length > 2 ||
mapper.params.some((param) => param.type === 'RestElement')
) {
return;
}
}
const spreadElement = arrayExpr.elements[0];
const iterableText = formatArguments(
[spreadElement.argument],
sourceCode
);
const mapperText = formatArguments([mapper], sourceCode);
context.report({
node,
messageId: 'preferArrayFrom',
fix(fixer) {
return fixer.replaceText(
node,
`Array.from(${iterableText}, ${mapperText})`
);
}
});
}
};
}
};