Skip to content

Commit

Permalink
Fix: handle array-destructuring with obj assignment in prefer const
Browse files Browse the repository at this point in the history
(fixes eslint#8308)
  • Loading branch information
VictorHom committed Sep 23, 2017
1 parent a7668c2 commit 08616bf
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 10 deletions.
11 changes: 11 additions & 0 deletions lib/rules/prefer-const.js
Expand Up @@ -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;
}

Expand Down
36 changes: 26 additions & 10 deletions tests/lib/rules/prefer-const.js
Expand Up @@ -56,16 +56,24 @@ 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 id;",
"function foo() {",
" if (typeof id !== 'undefined') {",
" return;",
" }",
" id = setInterval(() => {}, 250);",
"}",
"foo();"
].join("\n"),
"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;",
"function foo() {",
" if (typeof id !== 'undefined') {",
" return;",
" }",
" id = setInterval(() => {}, 250);",
"}",
"foo();"
].join("\n")
},
"/*exported a*/ let a; function init() { a = foo(); }",
"/*exported a*/ let a = 1",
"let a; if (true) a = 0; foo(a);",
Expand Down Expand Up @@ -268,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",
Expand Down

0 comments on commit 08616bf

Please sign in to comment.