Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: unexpected autofix in prefer-const (fixes #12514) #12521

Merged
merged 1 commit into from Nov 4, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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" }
]
}
]
});