2 * @fileoverview Prefer destructuring from arrays and objects
3 * @author Alex LaFroscia
7 //------------------------------------------------------------------------------
9 //------------------------------------------------------------------------------
11 const astUtils
= require("./utils/ast-utils");
13 //------------------------------------------------------------------------------
15 //------------------------------------------------------------------------------
17 const PRECEDENCE_OF_ASSIGNMENT_EXPR
= astUtils
.getPrecedence({ type
: "AssignmentExpression" });
19 //------------------------------------------------------------------------------
21 //------------------------------------------------------------------------------
28 description
: "require destructuring from arrays and/or objects",
29 category
: "ECMAScript 6",
31 url
: "https://eslint.org/docs/rules/prefer-destructuring"
40 * old support {array: Boolean, object: Boolean}
41 * new support {VariableDeclarator: {}, AssignmentExpression: {}}
57 additionalProperties
: false
59 AssignmentExpression
: {
69 additionalProperties
: false
72 additionalProperties
: false
84 additionalProperties
: false
91 enforceForRenamedProperties
: {
95 additionalProperties
: false
100 preferDestructuring
: "Use {{type}} destructuring."
105 const enabledTypes
= context
.options
[0];
106 const enforceForRenamedProperties
= context
.options
[1] && context
.options
[1].enforceForRenamedProperties
;
107 let normalizedOptions
= {
108 VariableDeclarator
: { array
: true, object
: true },
109 AssignmentExpression
: { array
: true, object
: true }
113 normalizedOptions
= typeof enabledTypes
.array
!== "undefined" || typeof enabledTypes
.object
!== "undefined"
114 ? { VariableDeclarator
: enabledTypes
, AssignmentExpression
: enabledTypes
}
118 //--------------------------------------------------------------------------
120 //--------------------------------------------------------------------------
122 // eslint-disable-next-line jsdoc/require-description
124 * @param {string} nodeType "AssignmentExpression" or "VariableDeclarator"
125 * @param {string} destructuringType "array" or "object"
126 * @returns {boolean} `true` if the destructuring type should be checked for the given node
128 function shouldCheck(nodeType
, destructuringType
) {
129 return normalizedOptions
&&
130 normalizedOptions
[nodeType
] &&
131 normalizedOptions
[nodeType
][destructuringType
];
135 * Determines if the given node is accessing an array index
137 * This is used to differentiate array index access from object property
139 * @param {ASTNode} node the node to evaluate
140 * @returns {boolean} whether or not the node is an integer
142 function isArrayIndexAccess(node
) {
143 return Number
.isInteger(node
.property
.value
);
147 * Report that the given node should use destructuring
148 * @param {ASTNode} reportNode the node to report
149 * @param {string} type the type of destructuring that should have been done
150 * @param {Function|null} fix the fix function or null to pass to context.report
153 function report(reportNode
, type
, fix
) {
156 messageId
: "preferDestructuring",
163 * Determines if a node should be fixed into object destructuring
165 * The fixer only fixes the simplest case of object destructuring,
166 * like: `let x = a.x`;
168 * Assignment expression is not fixed.
169 * Array destructuring is not fixed.
170 * Renamed property is not fixed.
171 * @param {ASTNode} node the the node to evaluate
172 * @returns {boolean} whether or not the node should be fixed
174 function shouldFix(node
) {
175 return node
.type
=== "VariableDeclarator" &&
176 node
.id
.type
=== "Identifier" &&
177 node
.init
.type
=== "MemberExpression" &&
178 !node
.init
.computed
&&
179 node
.init
.property
.type
=== "Identifier" &&
180 node
.id
.name
=== node
.init
.property
.name
;
184 * Fix a node into object destructuring.
185 * This function only handles the simplest case of object destructuring,
186 * see {@link shouldFix}.
187 * @param {SourceCodeFixer} fixer the fixer object
188 * @param {ASTNode} node the node to be fixed.
189 * @returns {Object} a fix for the node
191 function fixIntoObjectDestructuring(fixer
, node
) {
192 const rightNode
= node
.init
;
193 const sourceCode
= context
.getSourceCode();
195 // Don't fix if that would remove any comments. Only comments inside `rightNode.object` can be preserved.
196 if (sourceCode
.getCommentsInside(node
).length
> sourceCode
.getCommentsInside(rightNode
.object
).length
) {
200 let objectText
= sourceCode
.getText(rightNode
.object
);
202 if (astUtils
.getPrecedence(rightNode
.object
) < PRECEDENCE_OF_ASSIGNMENT_EXPR
) {
203 objectText
= `(${objectText})`;
206 return fixer
.replaceText(
208 `{${rightNode.property.name}} = ${objectText}`
213 * Check that the `prefer-destructuring` rules are followed based on the
214 * given left- and right-hand side of the assignment.
216 * Pulled out into a separate method so that VariableDeclarators and
217 * AssignmentExpressions can share the same verification logic.
218 * @param {ASTNode} leftNode the left-hand side of the assignment
219 * @param {ASTNode} rightNode the right-hand side of the assignment
220 * @param {ASTNode} reportNode the node to report the error on
223 function performCheck(leftNode
, rightNode
, reportNode
) {
224 if (rightNode
.type
!== "MemberExpression" || rightNode
.object
.type
=== "Super") {
228 if (isArrayIndexAccess(rightNode
)) {
229 if (shouldCheck(reportNode
.type
, "array")) {
230 report(reportNode
, "array", null);
235 const fix
= shouldFix(reportNode
)
236 ? fixer
=> fixIntoObjectDestructuring(fixer
, reportNode
)
239 if (shouldCheck(reportNode
.type
, "object") && enforceForRenamedProperties
) {
240 report(reportNode
, "object", fix
);
244 if (shouldCheck(reportNode
.type
, "object")) {
245 const property
= rightNode
.property
;
248 (property
.type
=== "Literal" && leftNode
.name
=== property
.value
) ||
249 (property
.type
=== "Identifier" && leftNode
.name
=== property
.name
&& !rightNode
.computed
)
251 report(reportNode
, "object", fix
);
257 * Check if a given variable declarator is coming from an property access
258 * that should be using destructuring instead
259 * @param {ASTNode} node the variable declarator to check
262 function checkVariableDeclarator(node
) {
264 // Skip if variable is declared without assignment
269 // We only care about member expressions past this point
270 if (node
.init
.type
!== "MemberExpression") {
274 performCheck(node
.id
, node
.init
, node
);
278 * Run the `prefer-destructuring` check on an AssignmentExpression
279 * @param {ASTNode} node the AssignmentExpression node
282 function checkAssignmentExpression(node
) {
283 if (node
.operator
=== "=") {
284 performCheck(node
.left
, node
.right
, node
);
288 //--------------------------------------------------------------------------
290 //--------------------------------------------------------------------------
293 VariableDeclarator
: checkVariableDeclarator
,
294 AssignmentExpression
: checkAssignmentExpression