From 326a048a5cdd1145f26d684bb73fa2f7601c85b4 Mon Sep 17 00:00:00 2001 From: Weijia Wang <381152119@qq.com> Date: Tue, 31 Oct 2017 23:51:59 +0800 Subject: [PATCH] tools: add fixer for no-let-in-for-declaration MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/16642 Refs: https://github.com/nodejs/node/issues/16636 Reviewed-By: Anatoli Papirovski Reviewed-By: Gireesh Punathil Reviewed-By: Tobias Nießen --- .../test-eslint-no-let-in-for-declaration.js | 3 +++ tools/eslint-rules/no-let-in-for-declaration.js | 16 +++++++++++++--- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/test/parallel/test-eslint-no-let-in-for-declaration.js b/test/parallel/test-eslint-no-let-in-for-declaration.js index b6b7c357455ab9..c3c1e17a729252 100644 --- a/test/parallel/test-eslint-no-let-in-for-declaration.js +++ b/test/parallel/test-eslint-no-let-in-for-declaration.js @@ -24,14 +24,17 @@ ruleTester.run('no-let-in-for-declaration', rule, { invalid: [ { code: 'for (let foo = 1;;);', + output: 'for (var foo = 1;;);', errors: [{ message }] }, { code: 'for (let foo in bar);', + output: 'for (var foo in bar);', errors: [{ message }] }, { code: 'for (let foo of bar);', + output: 'for (var foo of bar);', errors: [{ message }] } ] diff --git a/tools/eslint-rules/no-let-in-for-declaration.js b/tools/eslint-rules/no-let-in-for-declaration.js index 8b1a6783e0773d..34ad2d5761fda2 100644 --- a/tools/eslint-rules/no-let-in-for-declaration.js +++ b/tools/eslint-rules/no-let-in-for-declaration.js @@ -14,7 +14,7 @@ module.exports = { create(context) { - + const sourceCode = context.getSourceCode(); const msg = 'Use of `let` as the loop variable in a for-loop is ' + 'not recommended. Please use `var` instead.'; @@ -23,7 +23,12 @@ module.exports = { */ function testForLoop(node) { if (node.init && node.init.kind === 'let') { - context.report(node.init, msg); + context.report({ + node: node.init, + message: msg, + fix: (fixer) => + fixer.replaceText(sourceCode.getFirstToken(node.init), 'var') + }); } } @@ -33,7 +38,12 @@ module.exports = { */ function testForInOfLoop(node) { if (node.left && node.left.kind === 'let') { - context.report(node.left, msg); + context.report({ + node: node.left, + message: msg, + fix: (fixer) => + fixer.replaceText(sourceCode.getFirstToken(node.left), 'var') + }); } }