Skip to content

Commit

Permalink
fix(eslint-plugin): [no-magic-numbers] Support negative numbers (type…
Browse files Browse the repository at this point in the history
…script-eslint#1072)



Co-authored-by: Brad Zacher <brad.zacher@gmail.com>
  • Loading branch information
a-tarasyuk and bradzacher committed Oct 16, 2019
1 parent 16adda4 commit 0c85ac3
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 11 deletions.
55 changes: 44 additions & 11 deletions packages/eslint-plugin/src/rules/no-magic-numbers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,11 +160,23 @@ export default util.createRule<Options, MessageIds>({
* @private
*/
function isParentTSReadonlyClassProperty(node: TSESTree.Node): boolean {
return (
!!node.parent &&
if (
node.parent &&
node.parent.type === AST_NODE_TYPES.UnaryExpression &&
['-', '+'].includes(node.parent.operator)
) {
node = node.parent;
}

if (
node.parent &&
node.parent.type === AST_NODE_TYPES.ClassProperty &&
!!node.parent.readonly
);
node.parent.readonly
) {
return true;
}

return false;
}

return {
Expand All @@ -174,13 +186,6 @@ export default util.createRule<Options, MessageIds>({
return;
}

if (
options.ignoreReadonlyClassProperties &&
isParentTSReadonlyClassProperty(node)
) {
return;
}

// Check TypeScript specific nodes for Numeric Literal
if (
options.ignoreNumericLiteralTypes &&
Expand All @@ -190,6 +195,34 @@ export default util.createRule<Options, MessageIds>({
return;
}

// Check if the node is a readonly class property
if (isNumber(node) && isParentTSReadonlyClassProperty(node)) {
if (options.ignoreReadonlyClassProperties) {
return;
}

let fullNumberNode:
| TSESTree.Literal
| TSESTree.UnaryExpression = node;
let raw = node.raw;

if (
node.parent &&
node.parent.type === AST_NODE_TYPES.UnaryExpression
) {
fullNumberNode = node.parent;
raw = `${node.parent.operator}${node.raw}`;
}

context.report({
messageId: 'noMagic',
node: fullNumberNode,
data: { raw },
});

return;
}

// Let the base rule deal with the rest
rules.Literal(node);
},
Expand Down
14 changes: 14 additions & 0 deletions packages/eslint-plugin/tests/rules/no-magic-numbers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ class Foo {
readonly B = 2;
public static readonly C = 1;
static readonly D = 1;
readonly E = -1;
readonly F = +1;
}
`,
options: [{ ignoreReadonlyClassProperties: true }],
Expand Down Expand Up @@ -184,6 +186,8 @@ class Foo {
readonly B = 2;
public static readonly C = 1;
static readonly D = 1;
readonly E = -1;
readonly F = +1;
}
`,
options: [{ ignoreReadonlyClassProperties: false }],
Expand All @@ -208,6 +212,16 @@ class Foo {
line: 6,
column: 23,
},
{
messageId: 'noMagic',
line: 7,
column: 16,
},
{
messageId: 'noMagic',
line: 8,
column: 16,
},
],
},
],
Expand Down

0 comments on commit 0c85ac3

Please sign in to comment.