forked from sindresorhus/eslint-plugin-unicorn
/
prefer-object-from-entries.js
274 lines (239 loc) · 7.87 KB
/
prefer-object-from-entries.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
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
'use strict';
const {isCommaToken, isArrowToken, isClosingParenToken} = require('eslint-utils');
const getDocumentationUrl = require('./utils/get-documentation-url.js');
const {matches, methodCallSelector} = require('./selectors/index.js');
const {getParentheses, getParenthesizedText} = require('./utils/parentheses.js');
const {isNodeMatches, isNodeMatchesNameOrPath} = require('./utils/is-node-matches.js');
const MESSAGE_ID_REDUCE = 'reduce';
const MESSAGE_ID_FUNCTION = 'function';
const messages = {
[MESSAGE_ID_REDUCE]: 'Prefer `Object.fromEntries()` over `Array#reduce()`.',
[MESSAGE_ID_FUNCTION]: 'Prefer `Object.fromEntries()` over `{{functionName}}()`.',
};
const createEmptyObjectSelector = path => {
const prefix = path ? `${path}.` : '';
return matches([
// `{}`
`[${prefix}type="ObjectExpression"][${prefix}properties.length=0]`,
// `Object.create(null)`
[
methodCallSelector({path, object: 'Object', method: 'create', argumentsLength: 1}),
`[${prefix}arguments.0.type="Literal"]`,
`[${prefix}arguments.0.raw="null"]`,
].join(''),
]);
};
const createArrowCallbackSelector = path => {
const prefix = path ? `${path}.` : '';
return [
`[${prefix}type="ArrowFunctionExpression"]`,
`[${prefix}async!=true]`,
`[${prefix}generator!=true]`,
`[${prefix}params.length>=1]`,
`[${prefix}params.0.type="Identifier"]`,
].join('');
};
const createPropertySelector = path => {
const prefix = path ? `${path}.` : '';
return [
`[${prefix}type="Property"]`,
`[${prefix}kind="init"]`,
`[${prefix}method!=true]`,
].join('');
};
// - `pairs.reduce(…, {})`
// - `pairs.reduce(…, Object.create(null))`
const arrayReduceWithEmptyObject = [
methodCallSelector({method: 'reduce', argumentsLength: 2}),
createEmptyObjectSelector('arguments.1'),
].join('');
const fixableArrayReduceCases = [
{
selector: [
arrayReduceWithEmptyObject,
// () => Object.assign(object, {key})
createArrowCallbackSelector('arguments.0'),
methodCallSelector({path: 'arguments.0.body', object: 'Object', method: 'assign', argumentsLength: 2}),
'[arguments.0.body.arguments.0.type="Identifier"]',
'[arguments.0.body.arguments.1.type="ObjectExpression"]',
'[arguments.0.body.arguments.1.properties.length=1]',
createPropertySelector('arguments.0.body.arguments.1.properties.0'),
].join(''),
test: callback => callback.params[0].name === callback.body.arguments[0].name,
getProperty: callback => callback.body.arguments[1].properties[0],
},
{
selector: [
arrayReduceWithEmptyObject,
// () => ({...object, key})
createArrowCallbackSelector('arguments.0'),
'[arguments.0.body.type="ObjectExpression"]',
'[arguments.0.body.properties.length=2]',
'[arguments.0.body.properties.0.type="SpreadElement"]',
'[arguments.0.body.properties.0.argument.type="Identifier"]',
createPropertySelector('arguments.0.body.properties.1'),
].join(''),
test: callback => callback.params[0].name === callback.body.properties[0].argument.name,
getProperty: callback => callback.body.properties[1],
},
];
// `_.flatten(array)`
const lodashFromPairsFunctions = [
'_.fromPairs',
'lodash.fromPairs',
];
const anyCall = [
'CallExpression',
'[optional!=true]',
'[arguments.length=1]',
'[arguments.0.type!="SpreadElement"]',
' > .callee',
].join('');
function fixReduceAssignOrSpread({sourceCode, node, property}) {
const removeInitObject = fixer => {
const initObject = node.arguments[1];
const parentheses = getParentheses(initObject, sourceCode);
const firstToken = parentheses[0] || initObject;
const lastToken = parentheses[parentheses.length - 1] || initObject;
const startToken = sourceCode.getTokenBefore(firstToken);
const [start] = startToken.range;
const [, end] = lastToken.range;
return fixer.replaceTextRange([start, end], '');
};
function * removeFirstParameter(fixer) {
const parameters = node.arguments[0].params;
const [firstParameter] = parameters;
const tokenAfter = sourceCode.getTokenAfter(firstParameter);
if (isCommaToken(tokenAfter)) {
yield fixer.remove(tokenAfter);
}
let shouldAddParentheses = false;
if (parameters.length === 1) {
const arrowToken = sourceCode.getTokenAfter(firstParameter, isArrowToken);
const tokenBeforeArrowToken = sourceCode.getTokenBefore(arrowToken);
if (!isClosingParenToken(tokenBeforeArrowToken)) {
shouldAddParentheses = true;
}
}
yield fixer.replaceText(firstParameter, shouldAddParentheses ? '()' : '');
}
const getKeyValueText = () => {
const {key, value} = property;
let keyText = getParenthesizedText(key, sourceCode);
const valueText = getParenthesizedText(value, sourceCode);
if (!property.computed && key.type === 'Identifier') {
keyText = `'${keyText}'`;
}
return {keyText, valueText};
};
function * replaceFunctionBody(fixer) {
const functionBody = node.arguments[0].body;
const {keyText, valueText} = getKeyValueText();
yield fixer.replaceText(functionBody, `[${keyText}, ${valueText}]`);
for (const parentheses of getParentheses(functionBody, sourceCode)) {
yield fixer.remove(parentheses);
}
}
return function * (fixer) {
// Wrap `array.reduce()` with `Object.fromEntries()`
yield fixer.insertTextBefore(node, 'Object.fromEntries(');
yield fixer.insertTextAfter(node, ')');
// Switch `.reduce` to `.map`
yield fixer.replaceText(node.callee.property, 'map');
// Remove empty object
yield removeInitObject(fixer);
// Remove the first parameter
yield * removeFirstParameter(fixer);
// Replace function body
yield * replaceFunctionBody(fixer);
};
}
/** @param {import('eslint').Rule.RuleContext} context */
function create(context) {
const {functions: configFunctions} = {
functions: [],
...context.options[0],
};
const functions = [...configFunctions, ...lodashFromPairsFunctions];
const sourceCode = context.getSourceCode();
const listeners = {};
const arrayReduce = new Map();
for (const {selector, test, getProperty} of fixableArrayReduceCases) {
listeners[selector] = node => {
// If this listener exits without adding a fix, the `arrayReduceWithEmptyObject` listener
// should still add it into the `arrayReduce` map. To be safer, add it here too.
arrayReduce.set(node, undefined);
const [callbackFunction] = node.arguments;
if (!test(callbackFunction)) {
return;
}
const [firstParameter] = callbackFunction.params;
const variables = context.getDeclaredVariables(callbackFunction);
const firstParameterVariable = variables.find(variable => variable.identifiers.length === 1 && variable.identifiers[0] === firstParameter);
if (!firstParameterVariable || firstParameterVariable.references.length !== 1) {
return;
}
arrayReduce.set(
node,
// The fix function
fixReduceAssignOrSpread({
sourceCode,
node,
property: getProperty(callbackFunction),
}),
);
};
}
listeners[arrayReduceWithEmptyObject] = node => {
if (!arrayReduce.has(node)) {
arrayReduce.set(node, undefined);
}
};
listeners['Program:exit'] = () => {
for (const [node, fix] of arrayReduce.entries()) {
context.report({
node: node.callee.property,
messageId: MESSAGE_ID_REDUCE,
fix,
});
}
};
listeners[anyCall] = node => {
if (!isNodeMatches(node, functions)) {
return;
}
const functionName = functions.find(nameOrPath => isNodeMatchesNameOrPath(node, nameOrPath)).trim();
context.report({
node,
messageId: MESSAGE_ID_FUNCTION,
data: {functionName},
fix: fixer => fixer.replaceText(node, 'Object.fromEntries'),
});
};
return listeners;
}
const schema = [
{
type: 'object',
additionalProperties: false,
properties: {
functions: {
type: 'array',
uniqueItems: true,
},
},
},
];
module.exports = {
create,
meta: {
type: 'suggestion',
docs: {
description: 'Prefer using `Object.fromEntries(…)` to transform a list of key-value pairs into an object.',
url: getDocumentationUrl(__filename),
},
fixable: 'code',
schema,
messages,
},
};