Skip to content

Commit

Permalink
Fix: prefer-destructuring invalid autofix with comma operator (#13761)
Browse files Browse the repository at this point in the history
  • Loading branch information
mdjermanovic committed Oct 23, 2020
1 parent 1a9f171 commit 3175316
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 1 deletion.
20 changes: 19 additions & 1 deletion lib/rules/prefer-destructuring.js
Expand Up @@ -4,6 +4,18 @@
*/
"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

const astUtils = require("./utils/ast-utils");

//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------

const PRECEDENCE_OF_ASSIGNMENT_EXPR = astUtils.getPrecedence({ type: "AssignmentExpression" });

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
Expand Down Expand Up @@ -185,9 +197,15 @@ module.exports = {
return null;
}

let objectText = sourceCode.getText(rightNode.object);

if (astUtils.getPrecedence(rightNode.object) < PRECEDENCE_OF_ASSIGNMENT_EXPR) {
objectText = `(${objectText})`;
}

return fixer.replaceText(
node,
`{${rightNode.property.name}} = ${sourceCode.getText(rightNode.object)}`
`{${rightNode.property.name}} = ${objectText}`
);
}

Expand Down
45 changes: 45 additions & 0 deletions tests/lib/rules/prefer-destructuring.js
Expand Up @@ -188,6 +188,51 @@ ruleTester.run("prefer-destructuring", rule, {
type: "VariableDeclarator"
}]
},
{
code: "var foo = (a, b).foo;",
output: "var {foo} = (a, b);",
errors: [{
messageId: "preferDestructuring",
data: { type: "object" },
type: "VariableDeclarator"
}]
},
{
code: "var length = (() => {}).length;",
output: "var {length} = () => {};",
errors: [{
messageId: "preferDestructuring",
data: { type: "object" },
type: "VariableDeclarator"
}]
},
{
code: "var foo = (a = b).foo;",
output: "var {foo} = a = b;",
errors: [{
messageId: "preferDestructuring",
data: { type: "object" },
type: "VariableDeclarator"
}]
},
{
code: "var foo = (a || b).foo;",
output: "var {foo} = a || b;",
errors: [{
messageId: "preferDestructuring",
data: { type: "object" },
type: "VariableDeclarator"
}]
},
{
code: "var foo = (f()).foo;",
output: "var {foo} = f();",
errors: [{
messageId: "preferDestructuring",
data: { type: "object" },
type: "VariableDeclarator"
}]
},
{
code: "var foo = object.bar.foo;",
output: "var {foo} = object.bar;",
Expand Down

0 comments on commit 3175316

Please sign in to comment.