From ac606217d4beebc35b865d14a7f9723fd21faa48 Mon Sep 17 00:00:00 2001 From: YeonJuan Date: Tue, 5 Nov 2019 03:15:57 +0900 Subject: [PATCH] Fix: unexpected autofix in prefer-const (fixes #12514) (#12521) --- lib/rules/prefer-const.js | 21 ++++++++++++++------- tests/lib/rules/prefer-const.js | 19 +++++++++++++++++++ 2 files changed, 33 insertions(+), 7 deletions(-) diff --git a/lib/rules/prefer-const.js b/lib/rules/prefer-const.js index 87f83892126..439a4db3c96 100644 --- a/lib/rules/prefer-const.js +++ b/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; + } } } } diff --git a/tests/lib/rules/prefer-const.js b/tests/lib/rules/prefer-const.js index d923985337b..ad25f5f4830 100644 --- a/tests/lib/rules/prefer-const.js +++ b/tests/lib/rules/prefer-const.js @@ -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" } + ] } ] });