Skip to content

Commit 9a6012c

Browse files
authored
no-nested-ternary: Use simple selector (#2115)
1 parent 2b05e38 commit 9a6012c

File tree

1 file changed

+33
-22
lines changed

1 file changed

+33
-22
lines changed

rules/no-nested-ternary.js

Lines changed: 33 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -8,30 +8,41 @@ const messages = {
88
[MESSAGE_ID_SHOULD_PARENTHESIZED]: 'Nest ternary expression should be parenthesized.',
99
};
1010

11-
const nestTernarySelector = level => `:not(ConditionalExpression)${' > ConditionalExpression'.repeat(level)}`;
12-
1311
/** @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+
}
1621

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+
});
3546

3647
/** @type {import('eslint').Rule.RuleModule} */
3748
module.exports = {

0 commit comments

Comments
 (0)