Skip to content
Permalink
Browse files

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

  • Loading branch information
yeonjuan authored and kaicataldo committed Nov 4, 2019
1 parent 990065e commit ac606217d4beebc35b865d14a7f9723fd21faa48
Showing with 33 additions and 7 deletions.
  1. +14 −7 lib/rules/prefer-const.js
  2. +19 −0 tests/lib/rules/prefer-const.js
@@ -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
@@ -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;
}
}
}
}
@@ -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.
You can’t perform that action at this time.