diff --git a/lib/rules/no-magic-numbers.js b/lib/rules/no-magic-numbers.js index 4bf24996cb8..5dd6feaab0d 100644 --- a/lib/rules/no-magic-numbers.js +++ b/lib/rules/no-magic-numbers.js @@ -110,11 +110,14 @@ module.exports = { /** * Returns whether the number should be ignored when used as an array index with enabled 'ignoreArrayIndexes' option. - * @param {ASTNode} parent the non-"UnaryExpression" parent. + * @param {ASTNode} node Node to check * @returns {boolean} true if the number should be ignored */ - function shouldIgnoreArrayIndexes(parent) { - return parent.type === "MemberExpression" && ignoreArrayIndexes; + function shouldIgnoreArrayIndexes(node) { + const parent = node.parent; + + return ignoreArrayIndexes && + parent.type === "MemberExpression" && parent.property === node; } return { @@ -145,7 +148,7 @@ module.exports = { if (shouldIgnoreNumber(value) || shouldIgnoreParseInt(parent, fullNumberNode) || - shouldIgnoreArrayIndexes(parent) || + shouldIgnoreArrayIndexes(fullNumberNode) || shouldIgnoreJSXNumbers(parent)) { return; } diff --git a/tests/lib/rules/no-magic-numbers.js b/tests/lib/rules/no-magic-numbers.js index bda02662edf..5935ac79b2e 100644 --- a/tests/lib/rules/no-magic-numbers.js +++ b/tests/lib/rules/no-magic-numbers.js @@ -85,6 +85,27 @@ ruleTester.run("no-magic-numbers", rule, { code: "f(-100n)", options: [{ ignore: ["-100n"] }], parserOptions: { ecmaVersion: 2020 } + }, + + // Regression tests to preserve the behavior of ignoreArrayIndexes. + { + code: "var foo = bar[-100];", + options: [{ + ignoreArrayIndexes: true + }] + }, + { + code: "var foo = bar[1.5];", + options: [{ + ignoreArrayIndexes: true + }] + }, + { + code: "var foo = bar[100n];", + options: [{ + ignoreArrayIndexes: true + }], + parserOptions: { ecmaVersion: 2020 } } ], invalid: [ @@ -236,6 +257,24 @@ ruleTester.run("no-magic-numbers", rule, { messageId: "noMagic", data: { raw: "3" }, line: 1 }] }, + { + code: "100 .toString()", + options: [{ + ignoreArrayIndexes: true + }], + errors: [{ + messageId: "noMagic", data: { raw: "100" }, line: 1 + }] + }, + { + code: "200[100]", + options: [{ + ignoreArrayIndexes: true + }], + errors: [{ + messageId: "noMagic", data: { raw: "200" }, line: 1 + }] + }, { code: "var a =
;", parserOptions: {