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-nested-ternaries.js
91 lines (84 loc) · 2.06 KB
/
disallow-nested-ternaries.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
/**
* Disallows nested ternaries.
*
* Types: `Boolean`, `Object`
*
* Values: `true` or an Object that contains a `maxLevel` property equal to an integer
* indicating the maximum levels of nesting to be allowed.
*
* #### Examples
*
* ```js
* "disallowNestedTernaries": true
*
* // or
*
* "disallowNestedTernaries": { "maxLevel": 1 }
* ```
*
* ##### Valid for modes `true` and `"maxLevel": 1`
*
* ```js
* var foo = (a === b) ? 1 : 2;
* ```
*
* ##### Invalid for mode `true`, but valid for `"maxLevel": 1`
*
* ```js
* var foo = (a === b)
* ? (a === c)
* ? 1
* : 2
* : (b === c)
* ? 3
* : 4;
* ```
*
* ##### Invalid for modes `true` and `"maxLevel": 1`
*
* ```js
* var foo = (a === b)
* ? (a === c)
* ? (c === d)
* ? 5
* : 6
* : 2
* : (b === c)
* ? 3
* : 4;
* ```
*/
var assert = require('assert');
module.exports = function() {};
module.exports.prototype = {
configure: function(options) {
assert(
options === true || (typeof options.maxLevel === 'number' && options.maxLevel > 0),
this.getOptionName() + ' option requires a true value or an object with "maxLevel" property'
);
this._maxLevel = 0;
if (options.maxLevel) {
this._maxLevel = options.maxLevel;
}
},
getOptionName: function() {
return 'disallowNestedTernaries';
},
check: function(file, errors) {
var maxLevel = this._maxLevel;
file.iterateNodesByType('ConditionalExpression', function(node) {
var level = 0;
var getLevel = function(currentNode) {
if (currentNode.parentElement && currentNode.parentElement.type === 'ConditionalExpression') {
level += 1;
if (level > maxLevel) {
errors.add('Illegal nested ternary', node);
return;
}
getLevel(currentNode.parentElement);
}
};
getLevel(node);
});
}
};