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"
28 * Determines if a given node is an if-else without a condition on the else
29 * @param {ASTNode} node The node to check.
30 * @returns {boolean} True if the node has an else without an if.
33 function hasElseWithoutCondition(node) {
34 return node.alternate && node.alternate.type !== "IfStatement";
38 * Determines if a given node is a negated unary expression
39 * @param {Object} test The test object to check.
40 * @returns {boolean} True if the node is a negated unary expression.
43 function isNegatedUnaryExpression(test) {
44 return test.type === "UnaryExpression" && test.operator === "!";
48 * Determines if a given node is a negated binary expression
49 * @param {Test} test The test to check.
50 * @returns {boolean} True if the node is a negated binary expression.
53 function isNegatedBinaryExpression(test) {
54 return test.type === "BinaryExpression" &&
55 (test.operator === "!=" || test.operator === "!==");
59 * Determines if a given node has a negated if expression
60 * @param {ASTNode} node The node to check.
61 * @returns {boolean} True if the node has a negated if expression.
64 function isNegatedIf(node) {
65 return isNegatedUnaryExpression(node.test) || isNegatedBinaryExpression(node.test);
70 if (!hasElseWithoutCondition(node)) {
74 if (isNegatedIf(node)) {
75 context.report({ node, message: "Unexpected negated condition." });
78 ConditionalExpression(node) {
79 if (isNegatedIf(node)) {
80 context.report({ node, message: "Unexpected negated condition." });