]> git.proxmox.com Git - pve-eslint.git/blob - eslint/lib/rules/no-negated-condition.js
b5cbadca50f908dcd0541ae71c13b9d557e55071
[pve-eslint.git] / eslint / lib / rules / no-negated-condition.js
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
11 module.exports = {
12 meta: {
13 type: "suggestion",
14
15 docs: {
16 description: "disallow negated conditions",
17 recommended: false,
18 url: "https://eslint.org/docs/rules/no-negated-condition"
19 },
20
21 schema: [],
22
23 messages: {
24 unexpectedNegated: "Unexpected negated condition."
25 }
26 },
27
28 create(context) {
29
30 /**
31 * Determines if a given node is an if-else without a condition on the else
32 * @param {ASTNode} node The node to check.
33 * @returns {boolean} True if the node has an else without an if.
34 * @private
35 */
36 function hasElseWithoutCondition(node) {
37 return node.alternate && node.alternate.type !== "IfStatement";
38 }
39
40 /**
41 * Determines if a given node is a negated unary expression
42 * @param {Object} test The test object to check.
43 * @returns {boolean} True if the node is a negated unary expression.
44 * @private
45 */
46 function isNegatedUnaryExpression(test) {
47 return test.type === "UnaryExpression" && test.operator === "!";
48 }
49
50 /**
51 * Determines if a given node is a negated binary expression
52 * @param {Test} test The test to check.
53 * @returns {boolean} True if the node is a negated binary expression.
54 * @private
55 */
56 function isNegatedBinaryExpression(test) {
57 return test.type === "BinaryExpression" &&
58 (test.operator === "!=" || test.operator === "!==");
59 }
60
61 /**
62 * Determines if a given node has a negated if expression
63 * @param {ASTNode} node The node to check.
64 * @returns {boolean} True if the node has a negated if expression.
65 * @private
66 */
67 function isNegatedIf(node) {
68 return isNegatedUnaryExpression(node.test) || isNegatedBinaryExpression(node.test);
69 }
70
71 return {
72 IfStatement(node) {
73 if (!hasElseWithoutCondition(node)) {
74 return;
75 }
76
77 if (isNegatedIf(node)) {
78 context.report({
79 node,
80 messageId: "unexpectedNegated"
81 });
82 }
83 },
84 ConditionalExpression(node) {
85 if (isNegatedIf(node)) {
86 context.report({
87 node,
88 messageId: "unexpectedNegated"
89 });
90 }
91 }
92 };
93 }
94 };