/
prefer-spread.js
96 lines (81 loc) · 2.1 KB
/
prefer-spread.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
'use strict';
const getDocumentationUrl = require('./utils/get-documentation-url');
const methodSelector = require('./utils/method-selector');
const selector = [
methodSelector({
object: 'Array',
name: 'from',
min: 1,
max: 3
}),
// Allow `Array.from({length})`
'[arguments.0.type!="ObjectExpression"]'
].join('');
// https://github.com/eslint/espree/blob/6b7d0b8100537dcd5c84a7fb17bbe28edcabe05d/lib/token-translator.js#L20
const tokenTypesCantFollowOpenBracket = new Set([
'String',
'Null',
'Boolean',
'Numeric',
'RegularExpression'
]);
const create = context => {
const sourceCode = context.getSourceCode();
const getSource = node => sourceCode.getText(node);
const needsSemicolon = node => {
const tokenBefore = sourceCode.getTokenBefore(node);
if (tokenBefore) {
const {type, value} = tokenBefore;
if (type === 'Punctuator') {
if (value === ';') {
return false;
}
if (value === ']' || value === ')') {
return true;
}
}
if (tokenTypesCantFollowOpenBracket.has(type)) {
return true;
}
if (type === 'Template') {
return !value.endsWith('${');
}
const lastBlockNode = sourceCode.getNodeByRangeIndex(tokenBefore.range[0]);
if (lastBlockNode && lastBlockNode.type === 'ObjectExpression') {
return true;
}
// `for...of`
if (type === 'Identifier') {
return !(value === 'of' && lastBlockNode && lastBlockNode.type === 'ForOfStatement');
}
}
return false;
};
return {
[selector](node) {
context.report({
node,
message: 'Prefer the spread operator over `Array.from()`.',
fix: fixer => {
const [arrayLikeArgument, mapFn, thisArgument] = node.arguments.map(getSource);
let replacement = `${needsSemicolon(node) ? ';' : ''}[...${arrayLikeArgument}]`;
if (mapFn) {
const mapArguments = [mapFn, thisArgument].filter(Boolean);
replacement += `.map(${mapArguments.join(', ')})`;
}
return fixer.replaceText(node, replacement);
}
});
}
};
};
module.exports = {
create,
meta: {
type: 'suggestion',
docs: {
url: getDocumentationUrl(__filename)
},
fixable: 'code'
}
};