Repository navigation
Expand file tree
/
Copy pathprefer-spread-syntax.ts
More file actions
289 lines (267 loc) · 8.32 KB
/
Copy pathprefer-spread-syntax.ts
File metadata and controls
289 lines (267 loc) · 8.32 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
import type {TSESLint, TSESTree} from '@typescript-eslint/utils';
import {
getArrayKind,
isArrayType,
isIterableType
} from '../utils/typescript.js';
import {isSyntacticallyKnownArray} from '../utils/ast.js';
type MessageIds =
| 'preferSpreadArray'
| 'preferSpreadArrayFrom'
| 'preferSpreadObject'
| 'preferSpreadFunction';
function isNullOrUndefined(node: TSESTree.Expression): boolean {
if (node.type === 'Literal' && node.value === null) {
return true;
}
return node.type === 'Identifier' && node.name === 'undefined';
}
const nonArrayReturningMethods = new Set([
'charAt',
'charCodeAt',
'codePointAt',
'endsWith',
'includes',
'indexOf',
'join',
'lastIndexOf',
'localeCompare',
'normalize',
'padEnd',
'padStart',
'repeat',
'replace',
'replaceAll',
'startsWith',
'substring',
'toExponential',
'toFixed',
'toLocaleLowerCase',
'toLocaleString',
'toLocaleUpperCase',
'toLowerCase',
'toPrecision',
'toString',
'toUpperCase',
'trim',
'trimEnd',
'trimStart'
]);
const primitiveCoercionFunctions = new Set([
'BigInt',
'Boolean',
'Number',
'String'
]);
function isKnownNonArrayConcatReceiver(node: TSESTree.Node): boolean {
switch (node.type) {
case 'Literal':
case 'ObjectExpression':
case 'TemplateLiteral':
return true;
}
if (node.type !== 'CallExpression') {
return false;
}
const {callee} = node;
if (
callee.type === 'Identifier' &&
primitiveCoercionFunctions.has(callee.name)
) {
return true;
}
if (
callee.type !== 'MemberExpression' ||
callee.property.type !== 'Identifier'
) {
return false;
}
if (
callee.object.type === 'Identifier' &&
callee.object.name === 'JSON' &&
callee.property.name === 'stringify'
) {
return true;
}
return nonArrayReturningMethods.has(callee.property.name);
}
export const preferSpreadSyntax: TSESLint.RuleModule<MessageIds, []> = {
meta: {
type: 'suggestion',
docs: {
description:
'Prefer spread syntax over Array.concat(), Array.from(), Object.assign({}, ...), and Function.apply()'
},
fixable: 'code',
schema: [],
messages: {
preferSpreadArray:
'Use spread syntax [...arr, ...other] instead of arr.concat(other)',
preferSpreadArrayFrom:
'Use spread syntax [...iterable] instead of Array.from(iterable) when no mapper function is provided',
preferSpreadObject:
'Use spread syntax {...a, ...b} instead of Object.assign({}, a, b)',
preferSpreadFunction:
'Use spread syntax fn(...args) instead of fn.apply(null/undefined, args)'
}
},
defaultOptions: [],
create(context) {
const sourceCode = context.sourceCode;
return {
CallExpression(node: TSESTree.CallExpression) {
if (node.callee.type !== 'MemberExpression') {
return;
}
let messageId: MessageIds | undefined;
let replacement: string | undefined;
// array.concat()
// excluding Buffer.concat()
if (
node.callee.property.type === 'Identifier' &&
node.callee.property.name === 'concat' &&
node.arguments.length > 0 &&
!(
node.callee.object.type === 'Identifier' &&
node.callee.object.name === 'Buffer'
)
) {
const receiver = node.callee.object;
const receiverArrayType = isArrayType(receiver, context);
if (
receiverArrayType === false ||
(receiverArrayType !== true &&
isKnownNonArrayConcatReceiver(receiver))
) {
return;
}
const parts: string[] = [];
// For array literals, inline elements; otherwise spread
if (receiver.type === 'ArrayExpression') {
for (const el of receiver.elements) {
if (el) {
parts.push(sourceCode.getText(el));
}
}
} else {
parts.push(`...${sourceCode.getText(receiver)}`);
}
for (const arg of node.arguments) {
if (arg.type === 'SpreadElement') {
parts.push(sourceCode.getText(arg));
} else if (arg.type === 'ArrayExpression') {
for (const el of arg.elements) {
if (el) {
parts.push(sourceCode.getText(el));
}
}
} else {
const kind = getArrayKind(arg, context, true);
if (kind === 'ambiguous') {
return;
}
if (
kind === 'array' ||
(kind === 'unknown' && isSyntacticallyKnownArray(arg))
) {
parts.push(`...${sourceCode.getText(arg)}`);
} else {
parts.push(sourceCode.getText(arg));
}
}
}
replacement = `[${parts.join(', ')}]`;
messageId = 'preferSpreadArray';
}
// Array.from(iterable) with no mapper
else if (
node.callee.object.type === 'Identifier' &&
node.callee.object.name === 'Array' &&
node.callee.property.type === 'Identifier' &&
node.callee.property.name === 'from' &&
node.arguments.length === 1
) {
const firstArg = node.arguments[0]!;
if (
firstArg.type !== 'SpreadElement' &&
firstArg.type !== 'ObjectExpression' &&
isIterableType(firstArg, context) !== false
) {
const iterableText = sourceCode.getText(firstArg);
replacement = `[...${iterableText}]`;
messageId = 'preferSpreadArrayFrom';
}
}
// Object.assign({...}, ...)
else if (
node.callee.object.type === 'Identifier' &&
node.callee.object.name === 'Object' &&
node.callee.property.type === 'Identifier' &&
node.callee.property.name === 'assign' &&
node.arguments.length >= 2
) {
const firstArg = node.arguments[0]!;
if (
firstArg.type !== 'SpreadElement' &&
firstArg.type === 'ObjectExpression'
) {
const hasUnquotedProto = firstArg.properties.some(
(prop) =>
prop.type === 'Property' &&
!prop.computed &&
prop.key.type === 'Identifier' &&
prop.key.name === '__proto__'
);
if (!hasUnquotedProto) {
const restArgs = node.arguments.slice(1);
// If any argument is already a spread element (e.g. ...objs),
// we can't safely convert since Object.assign({}, ...objs) spreads
// array elements as individual arguments, which has no simple
// equivalent in object spread syntax.
if (restArgs.some((arg) => arg.type === 'SpreadElement')) {
return;
}
const spreadArgs = restArgs
.map((arg) => `...${sourceCode.getText(arg)}`)
.join(', ');
if (firstArg.properties.length === 0) {
replacement = `{${spreadArgs}}`;
} else {
const literalText = sourceCode.getText(firstArg);
const innerContent = literalText.slice(1, -1); // Remove { and }
replacement = `{${innerContent}, ${spreadArgs}}`;
}
messageId = 'preferSpreadObject';
}
}
}
// function.apply(null/undefined, args)
else if (
node.callee.property.type === 'Identifier' &&
node.callee.property.name === 'apply' &&
node.arguments.length === 2
) {
const firstArg = node.arguments[0]!;
if (
firstArg.type !== 'SpreadElement' &&
isNullOrUndefined(firstArg)
) {
const fnText = sourceCode.getText(node.callee.object);
const argsText = sourceCode.getText(node.arguments[1]!);
replacement = `${fnText}(...${argsText})`;
messageId = 'preferSpreadFunction';
}
}
if (messageId && replacement) {
context.report({
node,
messageId,
fix(fixer) {
return fixer.replaceText(node, replacement!);
}
});
}
}
};
}
};