diff --git a/docs/rules/radix.md b/docs/rules/radix.md index 64466ab6843..da3196c85f0 100644 --- a/docs/rules/radix.md +++ b/docs/rules/radix.md @@ -43,6 +43,8 @@ var num = parseInt(someValue); var num = parseInt("071", "abc"); +var num = parseInt("071", 37); + var num = parseInt(); ``` diff --git a/lib/rules/radix.js b/lib/rules/radix.js index ed3c5cb66b8..6cde887237b 100644 --- a/lib/rules/radix.js +++ b/lib/rules/radix.js @@ -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. @@ -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") ); } diff --git a/tests/lib/rules/radix.js b/tests/lib/rules/radix.js index 0acb063a347..18e74f37138 100644 --- a/tests/lib/rules/radix.js +++ b/tests/lib/rules/radix.js @@ -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: [{ @@ -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"],