Skip to content
This repository has been archived by the owner on Mar 25, 2021. It is now read-only.

no-magic-numbers rule ignores arguments in Number prototype methods #3668

Merged
16 changes: 12 additions & 4 deletions src/rules/noMagicNumbersRule.ts
Expand Up @@ -17,10 +17,12 @@

import * as ts from "typescript";

import { isCallExpression, isIdentifier } from "tsutils";
import { isCallExpression, isIdentifier, isPropertyAccessExpression } from "tsutils";
import * as Lint from "../index";
import { isNegativeNumberLiteral } from "../language/utils";

const NUMBER_METHODS = ["toExponential", "toFixed", "toPrecision", "toString"];

export class Rule extends Lint.Rules.AbstractRule {
/* tslint:disable:object-literal-sort-keys */
public static metadata: Lint.IRuleMetadata = {
Expand Down Expand Up @@ -61,7 +63,7 @@ export class Rule extends Lint.Rules.AbstractRule {
ts.SyntaxKind.Parameter,
]);

public static DEFAULT_ALLOWED = [ -1, 0, 1 ];
public static DEFAULT_ALLOWED = [-1, 0, 1];

public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithWalker(
Expand All @@ -77,8 +79,14 @@ export class Rule extends Lint.Rules.AbstractRule {
class NoMagicNumbersWalker extends Lint.AbstractWalker<number[]> {
public walk(sourceFile: ts.SourceFile) {
const cb = (node: ts.Node): void => {
if (isCallExpression(node) && isIdentifier(node.expression) && node.expression.text === "parseInt") {
return node.arguments.length === 0 ? undefined : cb(node.arguments[0]);
if (isCallExpression(node)) {
if (isIdentifier(node.expression) && node.expression.text === "parseInt") {
return node.arguments.length === 0 ? undefined : cb(node.arguments[0]);
}

if (isPropertyAccessExpression(node.expression) && NUMBER_METHODS.indexOf(node.expression.name.text) >= 0) {
return;
}
}

if (node.kind === ts.SyntaxKind.NumericLiteral) {
Expand Down
16 changes: 16 additions & 0 deletions test/rules/no-magic-numbers/default/test.ts.lint
Expand Up @@ -30,3 +30,19 @@ class A {
enum Test {
key = 1337,
}

const a = 0.1234567801234567890;
a.toFixed(2);
a.toFixed(5);
a.toFixed(10);

a.toString(10);
a.toString(36);

a.toPrecision(3)
a.toPrecision(10)
a.toPrecision(20)

const b = 77.1234;
b.toExponential(4);
b.toExponential(2);