Skip to content

Commit

Permalink
Update: fix no-magic-numbers false negative with ignoreArrayIndexes (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
mdjermanovic authored and kaicataldo committed Jan 28, 2020
1 parent f5b9656 commit 562e784
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 4 deletions.
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

0 comments on commit 562e784

Please sign in to comment.