UNPKG

2.78 kBJavaScriptView Raw
1/**
2 * @fileoverview Rule to flag unnecessary double negation in Boolean contexts
3 * @author Brandon Mills
4 */
5
6//------------------------------------------------------------------------------
7// Rule Definition
8//------------------------------------------------------------------------------
9
10module.exports = function(context) {
11
12 "use strict";
13
14 return {
15 "UnaryExpression": function (node) {
16 var ancestors = context.getAncestors(),
17 parent = ancestors.pop(),
18 grandparent = ancestors.pop(),
19 operator;
20
21 // Exit early if it's guaranteed not to match
22 if (node.operator !== "!" ||
23 parent.type !== "UnaryExpression" ||
24 parent.operator !== "!") {
25 return;
26 }
27
28 // if (<bool>) ...
29 if (grandparent.type === "IfStatement") {
30 context.report(node, "Redundant double negation in an if statement condition.");
31
32 // do ... while (<bool>)
33 } else if (grandparent.type === "DoWhileStatement") {
34 context.report(node, "Redundant double negation in a do while loop condition.");
35
36 // while (<bool>) ...
37 } else if (grandparent.type === "WhileStatement") {
38 context.report(node, "Redundant double negation in a while loop condition.");
39
40 // <bool> ? ... : ...
41 } else if ((grandparent.type === "ConditionalExpression" &&
42 parent === grandparent.test)) {
43 context.report(node, "Redundant double negation in a ternary condition.");
44
45 // for (...; <bool>; ...) ...
46 } else if ((grandparent.type === "ForStatement" &&
47 parent === grandparent.test)) {
48 context.report(node, "Redundant double negation in a for loop condition.");
49
50 // !<bool>
51 } else if ((grandparent.type === "UnaryExpression" &&
52 grandparent.operator === "!")) {
53 context.report(node, "Redundant multiple negation.");
54
55 // Boolean(<bool>)
56 } else if ((grandparent.type === "CallExpression" &&
57 grandparent.callee.type === "Identifier" &&
58 grandparent.callee.name === "Boolean")) {
59 context.report(node, "Redundant double negation in call to Boolean().");
60
61 // new Boolean(<bool>)
62 } else if ((grandparent.type === "NewExpression" &&
63 grandparent.callee.type === "Identifier" &&
64 grandparent.callee.name === "Boolean")) {
65 context.report(node, "Redundant double negation in Boolean constructor call.");
66 }
67 }
68 };
69
70};