UNPKG

3.03 kBJavaScriptView Raw
1/**
2 * @fileoverview Rule to flag use constant conditions
3 * @author Christian Schulz <http://rndm.de>
4 */
5
6
7//------------------------------------------------------------------------------
8// Rule Definition
9//------------------------------------------------------------------------------
10
11module.exports = function(context) {
12
13 "use strict";
14
15 // array of types that should always trigger this rule if used inside a condition
16 var alwaysSimpleConstantCondition = ["Literal", "FunctionExpression", "ObjectExpression", "ArrayExpression"],
17 // map of functions that should be called to determine if it is a constant condition
18 sometimesSimpleConstantCondition = {
19 /**
20 * Checks assignment expression for literal argument.
21 * @example returns true for: if (t = +2) { doSomething() }
22 * @param {ASTNode} field The AST node to check.
23 * @returns {Boolean} true if assignment has right side literal or identifier.
24 */
25 "AssignmentExpression": function(field) {
26 return (field.right.type === "Literal" ||
27 (field.right.type === "UnaryExpression" && field.right.argument.type === "Literal"));
28 },
29 /**
30 * Checks unary expression for literal argument.
31 * @example returns true for: if (+2) { doSomething(); }
32 * @param {ASTNode} field The AST node to check.
33 * @returns {Boolean} true if field has literal argument type.
34 */
35 "UnaryExpression": function(field) {
36 return field.argument.type === "Literal";
37 }
38 };
39
40 //--------------------------------------------------------------------------
41 // Helpers
42 //--------------------------------------------------------------------------
43
44 /**
45 * Checks if a node contains a constant condition.
46 * @param {ASTNode} node The AST node to check.
47 * @returns {void}
48 * @private
49 */
50 function checkConstantCondition(node) {
51 var field = node.test;
52 // check if type exists in simpleConditions array
53 if (alwaysSimpleConstantCondition.indexOf(field.type) !== -1 ||
54 // check if type exists in sometimes simple conditions
55 (sometimesSimpleConstantCondition.hasOwnProperty(field.type) &&
56 // check if type is a simple condition
57 sometimesSimpleConstantCondition[field.type](field))) {
58
59 context.report(node, "Unexpected constant condition.");
60 }
61 }
62
63 //--------------------------------------------------------------------------
64 // Public
65 //--------------------------------------------------------------------------
66
67 return {
68 "ConditionalExpression": checkConstantCondition,
69 "IfStatement": checkConstantCondition,
70 "WhileStatement": checkConstantCondition,
71 "DoWhileStatement": checkConstantCondition,
72 "ForStatement": checkConstantCondition
73 };
74
75};