Skip to content

Commit

Permalink
Update: make radix rule stricter
Browse files Browse the repository at this point in the history
  • Loading branch information
fisker committed Nov 27, 2019
1 parent fa6415d commit 860d826
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
2 changes: 2 additions & 0 deletions docs/rules/radix.md
Expand Up @@ -43,6 +43,8 @@ var num = parseInt(someValue);

var num = parseInt("071", "abc");

var num = parseInt("071", 37);

var num = parseInt();
```

Expand Down
7 changes: 5 additions & 2 deletions lib/rules/radix.js
Expand Up @@ -18,6 +18,8 @@ const astUtils = require("./utils/ast-utils");
const MODE_ALWAYS = "always",
MODE_AS_NEEDED = "as-needed";

const validRadixNumbers = new Set(Array.from({ length: 37 - 2 }, (_, index) => index + 2));

/**
* Checks whether a given variable is shadowed or not.
* @param {eslint-scope.Variable} variable A variable to check.
Expand All @@ -42,19 +44,20 @@ function isParseIntMethod(node) {
);
}


/**
* Checks whether a given node is a valid value of radix or not.
*
* The following values are invalid.
*
* - A literal except numbers.
* - A literal except integers between 2 and 36.
* - undefined.
* @param {ASTNode} radix A node of radix to check.
* @returns {boolean} `true` if the node is valid.
*/
function isValidRadix(radix) {
return !(
(radix.type === "Literal" && typeof radix.value !== "number") ||
(radix.type === "Literal" && !validRadixNumbers.has(radix.value)) ||
(radix.type === "Identifier" && radix.name === "undefined")
);
}
Expand Down
14 changes: 14 additions & 0 deletions tests/lib/rules/radix.js
Expand Up @@ -107,6 +107,13 @@ ruleTester.run("radix", rule, {
type: "CallExpression"
}]
},
{
code: "parseInt(\"10\", 37);",
errors: [{
message: "Invalid radix parameter.",
type: "CallExpression"
}]
},
{
code: "Number.parseInt();",
errors: [{
Expand All @@ -129,6 +136,13 @@ ruleTester.run("radix", rule, {
type: "CallExpression"
}]
},
{
code: "Number.parseInt(\"10\", 37);",
errors: [{
message: "Invalid radix parameter.",
type: "CallExpression"
}]
},
{
code: "parseInt(\"10\", 10);",
options: ["as-needed"],
Expand Down

0 comments on commit 860d826

Please sign in to comment.