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 //------------------------------------------------------------------------------
23 /** @type {import('../shared/types').Rule} */
29 description
: "Require destructuring from arrays and/or objects",
31 url
: "https://eslint.org/docs/latest/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 //--------------------------------------------------------------------------
123 * Checks if destructuring type should be checked.
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 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
.sourceCode
;
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
) {
225 rightNode
.type
!== "MemberExpression" ||
226 rightNode
.object
.type
=== "Super" ||
227 rightNode
.property
.type
=== "PrivateIdentifier"
232 if (isArrayIndexAccess(rightNode
)) {
233 if (shouldCheck(reportNode
.type
, "array")) {
234 report(reportNode
, "array", null);
239 const fix
= shouldFix(reportNode
)
240 ? fixer
=> fixIntoObjectDestructuring(fixer
, reportNode
)
243 if (shouldCheck(reportNode
.type
, "object") && enforceForRenamedProperties
) {
244 report(reportNode
, "object", fix
);
248 if (shouldCheck(reportNode
.type
, "object")) {
249 const property
= rightNode
.property
;
252 (property
.type
=== "Literal" && leftNode
.name
=== property
.value
) ||
253 (property
.type
=== "Identifier" && leftNode
.name
=== property
.name
&& !rightNode
.computed
)
255 report(reportNode
, "object", fix
);
261 * Check if a given variable declarator is coming from an property access
262 * that should be using destructuring instead
263 * @param {ASTNode} node the variable declarator to check
266 function checkVariableDeclarator(node
) {
268 // Skip if variable is declared without assignment
273 // We only care about member expressions past this point
274 if (node
.init
.type
!== "MemberExpression") {
278 performCheck(node
.id
, node
.init
, node
);
282 * Run the `prefer-destructuring` check on an AssignmentExpression
283 * @param {ASTNode} node the AssignmentExpression node
286 function checkAssignmentExpression(node
) {
287 if (node
.operator
=== "=") {
288 performCheck(node
.left
, node
.right
, node
);
292 //--------------------------------------------------------------------------
294 //--------------------------------------------------------------------------
297 VariableDeclarator
: checkVariableDeclarator
,
298 AssignmentExpression
: checkAssignmentExpression