From f5537b2ed0b0b5e51a34c22cdd4ebfd024eaea3d Mon Sep 17 00:00:00 2001 From: Milos Djermanovic Date: Wed, 25 Sep 2019 23:20:43 +0200 Subject: [PATCH] Fix: prefer-numeric-literals autofix removes comments (#12313) --- lib/rules/prefer-numeric-literals.js | 4 ++ tests/lib/rules/prefer-numeric-literals.js | 62 ++++++++++++++++++++++ 2 files changed, 66 insertions(+) diff --git a/lib/rules/prefer-numeric-literals.js b/lib/rules/prefer-numeric-literals.js index ca7358aa013..b4113a3b327 100644 --- a/lib/rules/prefer-numeric-literals.js +++ b/lib/rules/prefer-numeric-literals.js @@ -96,6 +96,10 @@ module.exports = { fix(fixer) { const newPrefix = prefixMap[node.arguments[1].value]; + if (sourceCode.getCommentsInside(node).length) { + return null; + } + if (+(newPrefix + node.arguments[0].value) !== parseInt(node.arguments[0].value, node.arguments[1].value)) { /* diff --git a/tests/lib/rules/prefer-numeric-literals.js b/tests/lib/rules/prefer-numeric-literals.js index e8401749062..800047051f3 100644 --- a/tests/lib/rules/prefer-numeric-literals.js +++ b/tests/lib/rules/prefer-numeric-literals.js @@ -90,6 +90,68 @@ ruleTester.run("prefer-numeric-literals", rule, { code: "Number.parseInt('1️⃣3️⃣3️⃣7️⃣', 16);", output: null, // not fixed, javascript doesn't support emoji literals errors: [{ message: "Use hexadecimal literals instead of Number.parseInt()." }] + }, + + // Should not autofix if it would remove comments + { + code: "/* comment */Number.parseInt('11', 2);", + output: "/* comment */0b11;", + errors: 1 + }, + { + code: "Number/**/.parseInt('11', 2);", + output: null, + errors: 1 + }, + { + code: "Number//\n.parseInt('11', 2);", + output: null, + errors: 1 + }, + { + code: "Number./**/parseInt('11', 2);", + output: null, + errors: 1 + }, + { + code: "Number.parseInt(/**/'11', 2);", + output: null, + errors: 1 + }, + { + code: "Number.parseInt('11', /**/2);", + output: null, + errors: 1 + }, + { + code: "Number.parseInt('11', 2)/* comment */;", + output: "0b11/* comment */;", + errors: 1 + }, + { + code: "parseInt/**/('11', 2);", + output: null, + errors: 1 + }, + { + code: "parseInt(//\n'11', 2);", + output: null, + errors: 1 + }, + { + code: "parseInt('11'/**/, 2);", + output: null, + errors: 1 + }, + { + code: "parseInt('11', 2 /**/);", + output: null, + errors: 1 + }, + { + code: "parseInt('11', 2)//comment\n;", + output: "0b11//comment\n;", + errors: 1 } ] });