Blame view

node_modules/eslint/lib/rules/no-constant-condition.js 2.37 KB
c39994410   Ryan Glover   wip converting to...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
  /**
   * @fileoverview Rule to flag use constant conditions
   * @author Christian Schulz <http://rndm.de>
   * @copyright 2014 Christian Schulz. All rights reserved.
   */
  
  "use strict";
  
  //------------------------------------------------------------------------------
  // Rule Definition
  //------------------------------------------------------------------------------
  
  module.exports = function(context) {
  
      //--------------------------------------------------------------------------
      // Helpers
      //--------------------------------------------------------------------------
  
      /**
       * Checks if a node has a constant truthiness value.
       * @param {ASTNode} node The AST node to check.
       * @returns {Bool} true when node's truthiness is constant
       * @private
       */
      function isConstant(node) {
          switch (node.type) {
              case "Literal":
              case "ArrowFunctionExpression":
              case "FunctionExpression":
              case "ObjectExpression":
              case "ArrayExpression":
                  return true;
              case "UnaryExpression":
                  return isConstant(node.argument);
              case "BinaryExpression":
              case "LogicalExpression":
                  return isConstant(node.left) && isConstant(node.right);
              case "AssignmentExpression":
                  return (node.operator === "=") && isConstant(node.right);
              case "SequenceExpression":
                  return isConstant(node.expressions[node.expressions.length - 1]);
              // no default
          }
          return false;
      }
  
      /**
       * Reports when the given node contains a constant condition.
       * @param {ASTNode} node The AST node to check.
       * @returns {void}
       * @private
       */
      function checkConstantCondition(node) {
          if (node.test && isConstant(node.test)) {
              context.report(node, "Unexpected constant condition.");
          }
      }
  
      //--------------------------------------------------------------------------
      // Public
      //--------------------------------------------------------------------------
  
      return {
          "ConditionalExpression": checkConstantCondition,
          "IfStatement": checkConstantCondition,
          "WhileStatement": checkConstantCondition,
          "DoWhileStatement": checkConstantCondition,
          "ForStatement": checkConstantCondition
      };
  
  };
  
  module.exports.schema = [];