Skip to content

Commit

Permalink
Fix: unexpected autofix in prefer-const (fixes #12514) (#12521)
Browse files Browse the repository at this point in the history
  • Loading branch information
yeonjuan authored and kaicataldo committed Nov 4, 2019
1 parent 990065e commit ac60621
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 7 deletions.
21 changes: 14 additions & 7 deletions lib/rules/prefer-const.js
Expand Up @@ -356,7 +356,9 @@ module.exports = {
const ignoreReadBeforeAssign = options.ignoreReadBeforeAssign === true;
const variables = [];
let reportCount = 0;
let name = "";
let checkedId = null;
let checkedName = "";


/**
* Reports given identifier nodes if all of the nodes should be declared
Expand Down Expand Up @@ -387,25 +389,30 @@ module.exports = {
/*
* First we check the declaration type and then depending on
* if the type is a "VariableDeclarator" or its an "ObjectPattern"
* we compare the name from the first identifier, if the names are different
* we assign the new name and reset the count of reportCount and nodeCount in
* we compare the name and id from the first identifier, if the names are different
* we assign the new name, id and reset the count of reportCount and nodeCount in
* order to check each block for the number of reported errors and base our fix
* based on comparing nodes.length and nodesToReport.length.
*/

if (firstDecParent.type === "VariableDeclarator") {

if (firstDecParent.id.name !== name) {
name = firstDecParent.id.name;
if (firstDecParent.id.name !== checkedName) {
checkedName = firstDecParent.id.name;
reportCount = 0;
}

if (firstDecParent.id.type === "ObjectPattern") {
if (firstDecParent.init.name !== name) {
name = firstDecParent.init.name;
if (firstDecParent.init.name !== checkedName) {
checkedName = firstDecParent.init.name;
reportCount = 0;
}
}

if (firstDecParent.id !== checkedId) {
checkedId = firstDecParent.id;
reportCount = 0;
}
}
}
}
Expand Down
19 changes: 19 additions & 0 deletions tests/lib/rules/prefer-const.js
Expand Up @@ -527,6 +527,25 @@ ruleTester.run("prefer-const", rule, {
{ messageId: "useConst", data: { name: "b" }, type: "Identifier" },
{ messageId: "useConst", data: { name: "c" }, type: "Identifier" }
]
},
{
code: [
"function a() {",
"let foo = 0,",
" bar = 1;",
"foo = 1;",
"}",
"function b() {",
"let foo = 0,",
" bar = 2;",
"foo = 2;",
"}"
].join("\n"),
output: null,
errors: [
{ message: "'bar' is never reassigned. Use 'const' instead.", type: "Identifier" },
{ message: "'bar' is never reassigned. Use 'const' instead.", type: "Identifier" }
]
}
]
});

0 comments on commit ac60621

Please sign in to comment.