UNPKG

2.65 kBJavaScriptView Raw
1/**
2 * @fileoverview Rule to disallow a negated condition
3 * @author Alberto Rodríguez
4 */
5"use strict";
6
7//------------------------------------------------------------------------------
8// Rule Definition
9//------------------------------------------------------------------------------
10
11module.exports = {
12 meta: {
13 docs: {
14 description: "disallow negated conditions",
15 category: "Stylistic Issues",
16 recommended: false
17 },
18
19 schema: []
20 },
21
22 create(context) {
23
24 /**
25 * Determines if a given node is an if-else without a condition on the else
26 * @param {ASTNode} node The node to check.
27 * @returns {boolean} True if the node has an else without an if.
28 * @private
29 */
30 function hasElseWithoutCondition(node) {
31 return node.alternate && node.alternate.type !== "IfStatement";
32 }
33
34 /**
35 * Determines if a given node is a negated unary expression
36 * @param {Object} test The test object to check.
37 * @returns {boolean} True if the node is a negated unary expression.
38 * @private
39 */
40 function isNegatedUnaryExpression(test) {
41 return test.type === "UnaryExpression" && test.operator === "!";
42 }
43
44 /**
45 * Determines if a given node is a negated binary expression
46 * @param {Test} test The test to check.
47 * @returns {boolean} True if the node is a negated binary expression.
48 * @private
49 */
50 function isNegatedBinaryExpression(test) {
51 return test.type === "BinaryExpression" &&
52 (test.operator === "!=" || test.operator === "!==");
53 }
54
55 /**
56 * Determines if a given node has a negated if expression
57 * @param {ASTNode} node The node to check.
58 * @returns {boolean} True if the node has a negated if expression.
59 * @private
60 */
61 function isNegatedIf(node) {
62 return isNegatedUnaryExpression(node.test) || isNegatedBinaryExpression(node.test);
63 }
64
65 return {
66 IfStatement(node) {
67 if (!hasElseWithoutCondition(node)) {
68 return;
69 }
70
71 if (isNegatedIf(node)) {
72 context.report({ node, message: "Unexpected negated condition." });
73 }
74 },
75 ConditionalExpression(node) {
76 if (isNegatedIf(node)) {
77 context.report({ node, message: "Unexpected negated condition." });
78 }
79 }
80 };
81 }
82};