UNPKG

2.51 kBJavaScriptView Raw
1/**
2 * Disallows the not, not equals, and strict not equals operators in conditionals.
3 *
4 * Type: `Boolean`
5 *
6 * Value: `true`
7 *
8 * #### Example
9 *
10 * ```js
11 * "disallowNotOperatorsInConditionals": true
12 * ```
13 *
14 * ##### Valid
15 *
16 * ```js
17 * if (clause) {
18 * // Do something really crazy
19 * } else {
20 * // Do something crazy
21 * }
22 *
23 * if (a == 1) {
24 * // Do something really crazy
25 * } else {
26 * // Do something crazy
27 * }
28 *
29 * var a = (clause) ? 1 : 0
30 * ```
31 *
32 * ##### Invalid
33 *
34 * ```js
35 * if (!clause) {
36 * // Do something crazy
37 * } else {
38 * // Do something really crazy
39 * }
40 *
41 * if (a != 1) {
42 * // Do something crazy
43 * } else {
44 * // Do something really crazy
45 * }
46 *
47 * if (a !== 1) {
48 * // Do something crazy
49 * } else {
50 * // Do something really crazy
51 * }
52 *
53 * var a = (!clause) ? 0 : 1
54 * ```
55 */
56
57var assert = require('assert');
58
59module.exports = function() {};
60
61module.exports.prototype = {
62
63 configure: function(options) {
64 assert(
65 options === true,
66 this.getOptionName() + ' option requires a true value or should be removed'
67 );
68 },
69
70 getOptionName: function() {
71 return 'disallowNotOperatorsInConditionals';
72 },
73
74 check: function(file, errors) {
75 function hasNotOperator(test) {
76 return test.type === 'UnaryExpression' && test.operator === '!';
77 }
78
79 function hasNotEqualOperator(test) {
80 return test.type === 'BinaryExpression' && test.operator === '!=';
81 }
82
83 function hasStrictNotEqualOperator(test) {
84 return test.type === 'BinaryExpression' && test.operator === '!==';
85 }
86
87 file.iterateNodesByType(['IfStatement', 'ConditionalExpression'], function(node) {
88 var alternate = node.alternate;
89
90 // check if the if statement has an else block
91 if (node.type === 'IfStatement' && (!alternate || alternate.type !== 'BlockStatement')) {
92 return;
93 }
94 var test = node.test;
95 if (hasNotOperator(test)) {
96 errors.add('Illegal use of not operator in if statement', test);
97 }
98 if (hasNotEqualOperator(test)) {
99 errors.add('Illegal use of not equal operator in if statement', test);
100 }
101 if (hasStrictNotEqualOperator(test)) {
102 errors.add('Illegal use of strict not equal operator in if statement', test);
103 }
104 });
105 }
106};