Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update: fix no-magic-numbers false negative with ignoreArrayIndexes #12805

Merged
merged 1 commit into from Jan 28, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 7 additions & 4 deletions lib/rules/no-magic-numbers.js
Expand Up @@ -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 {
Expand Down Expand Up @@ -145,7 +148,7 @@ module.exports = {

if (shouldIgnoreNumber(value) ||
shouldIgnoreParseInt(parent, fullNumberNode) ||
shouldIgnoreArrayIndexes(parent) ||
shouldIgnoreArrayIndexes(fullNumberNode) ||
shouldIgnoreJSXNumbers(parent)) {
return;
}
Expand Down
39 changes: 39 additions & 0 deletions tests/lib/rules/no-magic-numbers.js
Expand Up @@ -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: [
Expand Down Expand Up @@ -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 = <div arrayProp={[1,2,3]}></div>;",
parserOptions: {
Expand Down