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