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

Commit

Permalink
no-magic-numbers rule ignores arguments in Number prototype methods (#…
Browse files Browse the repository at this point in the history
…3668)

* no-magic-numbers rule ignores arguments in default Number prototype methods

* no-magic-numbers: tests moved from custom to default

* no-magic-numbers: Number method names defined in const instead of inside of a method

* Formatted noMagicNumbersRule.ts
  • Loading branch information
mateuszwitkowski authored and Josh Goldberg committed Jun 15, 2019
1 parent aa8c445 commit 484d429
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 7 deletions.
21 changes: 14 additions & 7 deletions src/rules/noMagicNumbersRule.ts
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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);

0 comments on commit 484d429

Please sign in to comment.