Skip to content
Permalink
Browse files

Fix: prefer-destructuring invalid autofix with comma operator (#13761)

  • Loading branch information
mdjermanovic committed Oct 23, 2020
1 parent 1a9f171 commit 3175316db26aebef4b19e269aca90c8ce3955363
Showing with 64 additions and 1 deletion.
  1. +19 −1 lib/rules/prefer-destructuring.js
  2. +45 −0 tests/lib/rules/prefer-destructuring.js
@@ -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
//------------------------------------------------------------------------------
@@ -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}`
);
}

@@ -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;",

0 comments on commit 3175316

Please sign in to comment.
You can’t perform that action at this time.