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
19 changes: 15 additions & 4 deletions src/rules/noMagicNumbersRule.ts
Expand Up @@ -17,7 +17,7 @@

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";

Expand Down Expand Up @@ -60,7 +60,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[] {
const allowedNumbers = this.ruleArguments.length > 0 ? this.ruleArguments : Rule.DEFAULT_ALLOWED;
Expand All @@ -71,8 +71,14 @@ export class Rule extends Lint.Rules.AbstractRule {
class NoMagicNumbersWalker extends Lint.AbstractWalker<Set<string>> {
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) && this.isNumberPrototypeMethod(node.expression.name.text)) {
return;
}
}

if (node.kind === ts.SyntaxKind.NumericLiteral) {
Expand All @@ -91,4 +97,9 @@ class NoMagicNumbersWalker extends Lint.AbstractWalker<Set<string>> {
this.addFailureAtNode(node, Rule.FAILURE_STRING);
}
}

private isNumberPrototypeMethod(methodName: string): boolean {
const numberMethods = ["toExponential", "toFixed", "toPrecision", "toString"];
JoshuaKGoldberg marked this conversation as resolved.
Show resolved Hide resolved
return numberMethods.indexOf(methodName) > -1;
}
}
17 changes: 17 additions & 0 deletions test/rules/no-magic-numbers/custom/test.ts.lint
Expand Up @@ -3,6 +3,23 @@ parseInt('123', 2);
parseInt('123', 8);
parseInt('123', 10);
parseInt('123', 16);

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)
JoshuaKGoldberg marked this conversation as resolved.
Show resolved Hide resolved

console.log(1337);
console.log(-1337);
console.log(- 1337);
Expand Down