2 * @fileoverview Rule to disallow a negated condition
3 * @author Alberto RodrÃguez
7 //------------------------------------------------------------------------------
9 //------------------------------------------------------------------------------
16 description: "disallow negated conditions",
17 category: "Stylistic Issues",
19 url: "https://eslint.org/docs/rules/no-negated-condition"
25 unexpectedNegated: "Unexpected negated condition."
32 * Determines if a given node is an if-else without a condition on the else
33 * @param {ASTNode} node The node to check.
34 * @returns {boolean} True if the node has an else without an if.
37 function hasElseWithoutCondition(node) {
38 return node.alternate && node.alternate.type !== "IfStatement";
42 * Determines if a given node is a negated unary expression
43 * @param {Object} test The test object to check.
44 * @returns {boolean} True if the node is a negated unary expression.
47 function isNegatedUnaryExpression(test) {
48 return test.type === "UnaryExpression" && test.operator === "!";
52 * Determines if a given node is a negated binary expression
53 * @param {Test} test The test to check.
54 * @returns {boolean} True if the node is a negated binary expression.
57 function isNegatedBinaryExpression(test) {
58 return test.type === "BinaryExpression" &&
59 (test.operator === "!=" || test.operator === "!==");
63 * Determines if a given node has a negated if expression
64 * @param {ASTNode} node The node to check.
65 * @returns {boolean} True if the node has a negated if expression.
68 function isNegatedIf(node) {
69 return isNegatedUnaryExpression(node.test) || isNegatedBinaryExpression(node.test);
74 if (!hasElseWithoutCondition(node)) {
78 if (isNegatedIf(node)) {
81 messageId: "unexpectedNegated"
85 ConditionalExpression(node) {
86 if (isNegatedIf(node)) {
89 messageId: "unexpectedNegated"