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