UNPKG

2.27 kBJavaScriptView Raw
1/**
2 * @fileoverview Rule to flag use of parseInt without a radix argument
3 * @author James Allardice
4 */
5
6"use strict";
7
8//------------------------------------------------------------------------------
9// Rule Definition
10//------------------------------------------------------------------------------
11
12module.exports = function(context) {
13
14 var MODE_ALWAYS = "always",
15 MODE_AS_NEEDED = "as-needed";
16
17 var mode = context.options[0] || MODE_ALWAYS;
18
19 return {
20 "CallExpression": function(node) {
21
22 var radix;
23
24 if (!(node.callee.name === "parseInt" || (
25 node.callee.type === "MemberExpression" &&
26 node.callee.object.name === "Number" &&
27 node.callee.property.name === "parseInt"
28 )
29 )) {
30 return;
31 }
32
33 if (node.arguments.length === 0) {
34 context.report({
35 node: node,
36 message: "Missing parameters."
37 });
38 } else if (node.arguments.length < 2 && mode === MODE_ALWAYS) {
39 context.report({
40 node: node,
41 message: "Missing radix parameter."
42 });
43 } else if (node.arguments.length > 1 && mode === MODE_AS_NEEDED &&
44 (node.arguments[1] && node.arguments[1].type === "Literal" &&
45 node.arguments[1].value === 10)
46 ) {
47 context.report({
48 node: node,
49 message: "Redundant radix parameter."
50 });
51 } else {
52
53 radix = node.arguments[1];
54
55 // don't allow non-numeric literals or undefined
56 if (radix &&
57 ((radix.type === "Literal" && typeof radix.value !== "number") ||
58 (radix.type === "Identifier" && radix.name === "undefined"))
59 ) {
60 context.report({
61 node: node,
62 message: "Invalid radix parameter."
63 });
64 }
65 }
66
67 }
68 };
69
70};
71
72module.exports.schema = [
73 {
74 "enum": ["always", "as-needed"]
75 }
76];
77