From 2cace0a8302f72fa1537cd0c7db66923fb3c21ff Mon Sep 17 00:00:00 2001 From: Victor Hom Date: Sun, 23 Jul 2017 21:34:24 -0400 Subject: [PATCH] Fix: handle array-destructuring with obj assignment in prefer const (fixes #8308) --- lib/rules/prefer-const.js | 11 +++++++++++ tests/lib/rules/prefer-const.js | 14 ++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/lib/rules/prefer-const.js b/lib/rules/prefer-const.js index 1395e0a8a08e..de98b022da4b 100644 --- a/lib/rules/prefer-const.js +++ b/lib/rules/prefer-const.js @@ -199,6 +199,17 @@ function groupByDestructuring(variables, ignoreReadBeforeAssign) { } } + for (const key of identifierMap.keys()) { + const destructureGroup = identifierMap.get(key); + const destructureElement = destructureGroup[0]; + + if (destructureElement && destructureElement.parent && destructureElement.parent.elements) { + if (destructureElement.parent.elements.length !== destructureGroup.length) { + identifierMap.delete(key); + } + } + } + return identifierMap; } diff --git a/tests/lib/rules/prefer-const.js b/tests/lib/rules/prefer-const.js index 984649cb415e..82ecfc1afa65 100644 --- a/tests/lib/rules/prefer-const.js +++ b/tests/lib/rules/prefer-const.js @@ -56,6 +56,12 @@ ruleTester.run("prefer-const", rule, { "let a; function foo() { if (a) {} a = bar(); }", "let a; function foo() { a = a || bar(); baz(a); }", "let a; function foo() { bar(++a); }", + "let predicate; [typeNode.returnType, predicate] = foo();", + "let predicate; let rest; [typeNode.returnType, predicate, ...rest] = foo();", + { + code: "let predicate; [typeNode.returnType, predicate] = foo();", + options: [{ destructuring: "all" }] + }, { code: [ "let id;", @@ -270,6 +276,14 @@ ruleTester.run("prefer-const", rule, { { message: "'a' is never reassigned. Use 'const' instead.", type: "Identifier" } ] }, + { + code: "let [ foo, bar ] = baz();", + output: "const [ foo, bar ] = baz();", + errors: [ + { message: "'foo' is never reassigned. Use 'const' instead.", type: "Identifier" }, + { message: "'bar' is never reassigned. Use 'const' instead.", type: "Identifier" } + ] + }, { code: "let {a} = obj", output: "const {a} = obj",