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
21 changes: 14 additions & 7 deletions src/rules/noMagicNumbersRule.ts
Expand Up @@ -15,12 +15,14 @@
* limitations under the License.
*/

import { isCallExpression, isIdentifier } from "tsutils";
import { isCallExpression, isIdentifier, isPropertyAccessExpression } from "tsutils";
import * as ts from "typescript";

import * as Lint from "../index";
import { isNegativeNumberLiteral } from "../language/utils";

const NUMBER_METHODS = new Set(["toExponential", "toFixed", "toPrecision", "toString"]);

interface AllowedNumbersType {
"allowed-numbers": number[];
}
Expand Down Expand Up @@ -140,12 +142,17 @@ function parseOptions(options: Array<OptionsType | number>): ParsedOptionsType {
class NoMagicNumbersWalker extends Lint.AbstractWalker<ParsedOptionsType | 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.has(node.expression.name.text)
) {
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);