2 * @fileoverview Rule to flag use constant conditions
3 * @author Christian Schulz <http://rndm.de>
4 * @copyright 2014 Christian Schulz. All rights reserved.
9 //------------------------------------------------------------------------------
11 //------------------------------------------------------------------------------
13 module.exports = function(context) {
15 //--------------------------------------------------------------------------
17 //--------------------------------------------------------------------------
20 * Checks if a node has a constant truthiness value.
21 * @param {ASTNode} node The AST node to check.
22 * @returns {Bool} true when node's truthiness is constant
25 function isConstant(node) {
28 case "ArrowFunctionExpression":
29 case "FunctionExpression":
30 case "ObjectExpression":
31 case "ArrayExpression":
33 case "UnaryExpression":
34 return isConstant(node.argument);
35 case "BinaryExpression":
36 case "LogicalExpression":
37 return isConstant(node.left) && isConstant(node.right);
38 case "AssignmentExpression":
39 return (node.operator === "=") && isConstant(node.right);
40 case "SequenceExpression":
41 return isConstant(node.expressions[node.expressions.length - 1]);
48 * Reports when the given node contains a constant condition.
49 * @param {ASTNode} node The AST node to check.
53 function checkConstantCondition(node) {
54 if (node.test && isConstant(node.test)) {
55 context.report(node, "Unexpected constant condition.");
59 //--------------------------------------------------------------------------
61 //--------------------------------------------------------------------------
64 "ConditionalExpression": checkConstantCondition,
65 "IfStatement": checkConstantCondition,
66 "WhileStatement": checkConstantCondition,
67 "DoWhileStatement": checkConstantCondition,
68 "ForStatement": checkConstantCondition