@@ -8,30 +8,41 @@ const messages = {
8
8
[ MESSAGE_ID_SHOULD_PARENTHESIZED ] : 'Nest ternary expression should be parenthesized.' ,
9
9
} ;
10
10
11
- const nestTernarySelector = level => `:not(ConditionalExpression)${ ' > ConditionalExpression' . repeat ( level ) } ` ;
12
-
13
11
/** @param {import('eslint').Rule.RuleContext } context */
14
- const create = context => {
15
- const { sourceCode} = context ;
12
+ const create = context => ( {
13
+ ConditionalExpression ( node ) {
14
+ if ( [
15
+ node . test ,
16
+ node . consequent ,
17
+ node . alternate ,
18
+ ] . some ( node => node . type === 'ConditionalExpression' ) ) {
19
+ return ;
20
+ }
16
21
17
- return {
18
- [ nestTernarySelector ( 3 ) ] : node =>
19
- // Nesting more than one level not allowed.
20
- ( { node, messageId : MESSAGE_ID_TOO_DEEP } ) ,
21
- [ nestTernarySelector ( 2 ) ] ( node ) {
22
- if ( ! isParenthesized ( node , sourceCode ) ) {
23
- return {
24
- node,
25
- messageId : MESSAGE_ID_SHOULD_PARENTHESIZED ,
26
- fix : fixer => [
27
- fixer . insertTextBefore ( node , '(' ) ,
28
- fixer . insertTextAfter ( node , ')' ) ,
29
- ] ,
30
- } ;
31
- }
32
- } ,
33
- } ;
34
- } ;
22
+ const { sourceCode} = context ;
23
+ const ancestors = sourceCode . getAncestors ( node ) . reverse ( ) ;
24
+ const nestLevel = ancestors . findIndex ( node => node . type !== 'ConditionalExpression' ) ;
25
+
26
+ if ( nestLevel === 1 && ! isParenthesized ( node , sourceCode ) ) {
27
+ return {
28
+ node,
29
+ messageId : MESSAGE_ID_SHOULD_PARENTHESIZED ,
30
+ fix : fixer => [
31
+ fixer . insertTextBefore ( node , '(' ) ,
32
+ fixer . insertTextAfter ( node , ')' ) ,
33
+ ] ,
34
+ } ;
35
+ }
36
+
37
+ // Nesting more than one level not allowed
38
+ if ( nestLevel > 1 ) {
39
+ return {
40
+ node : nestLevel > 2 ? ancestors [ nestLevel - 3 ] : node ,
41
+ messageId : MESSAGE_ID_TOO_DEEP ,
42
+ } ;
43
+ }
44
+ } ,
45
+ } ) ;
35
46
36
47
/** @type {import('eslint').Rule.RuleModule } */
37
48
module . exports = {
0 commit comments