2 * @fileoverview Rule to flag unnecessary double negation in Boolean contexts
3 * @author Brandon Mills
8 //------------------------------------------------------------------------------
10 //------------------------------------------------------------------------------
12 module.exports = function(context) {
15 "UnaryExpression": function (node) {
16 var ancestors = context.getAncestors(),
17 parent = ancestors.pop(),
18 grandparent = ancestors.pop();
20 // Exit early if it's guaranteed not to match
21 if (node.operator !== "!" ||
22 parent.type !== "UnaryExpression" ||
23 parent.operator !== "!") {
28 if (grandparent.type === "IfStatement") {
29 context.report(node, "Redundant double negation in an if statement condition.");
31 // do ... while (<bool>)
32 } else if (grandparent.type === "DoWhileStatement") {
33 context.report(node, "Redundant double negation in a do while loop condition.");
36 } else if (grandparent.type === "WhileStatement") {
37 context.report(node, "Redundant double negation in a while loop condition.");
40 } else if ((grandparent.type === "ConditionalExpression" &&
41 parent === grandparent.test)) {
42 context.report(node, "Redundant double negation in a ternary condition.");
44 // for (...; <bool>; ...) ...
45 } else if ((grandparent.type === "ForStatement" &&
46 parent === grandparent.test)) {
47 context.report(node, "Redundant double negation in a for loop condition.");
50 } else if ((grandparent.type === "UnaryExpression" &&
51 grandparent.operator === "!")) {
52 context.report(node, "Redundant multiple negation.");
55 } else if ((grandparent.type === "CallExpression" &&
56 grandparent.callee.type === "Identifier" &&
57 grandparent.callee.name === "Boolean")) {
58 context.report(node, "Redundant double negation in call to Boolean().");
60 // new Boolean(<bool>)
61 } else if ((grandparent.type === "NewExpression" &&
62 grandparent.callee.type === "Identifier" &&
63 grandparent.callee.name === "Boolean")) {
64 context.report(node, "Redundant double negation in Boolean constructor call.");