Skip to content

Commit 2b05e38

Browse files
authored
no-lonely-if: Use simple selector (#2114)
1 parent 808ec47 commit 2b05e38

File tree

1 file changed

+32
-30
lines changed

1 file changed

+32
-30
lines changed

rules/no-lonely-if.js

Lines changed: 32 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,14 @@
11
'use strict';
22
const {isParenthesized, isNotSemicolonToken} = require('@eslint-community/eslint-utils');
3-
const needsSemicolon = require('./utils/needs-semicolon.js');
3+
const {needsSemicolon} = require('./utils/index.js');
44
const {removeSpacesAfter} = require('./fix/index.js');
5-
const {matches} = require('./selectors/index.js');
65

76
const MESSAGE_ID = 'no-lonely-if';
87
const messages = {
98
[MESSAGE_ID]: 'Unexpected `if` as the only statement in a `if` block without `else`.',
109
};
1110

12-
const ifStatementWithoutAlternate = 'IfStatement:not([alternate])';
13-
const selector = matches([
14-
// `if (a) { if (b) {} }`
15-
[
16-
ifStatementWithoutAlternate,
17-
' > ',
18-
'BlockStatement.consequent',
19-
'[body.length=1]',
20-
' > ',
21-
`${ifStatementWithoutAlternate}.body`,
22-
].join(''),
23-
24-
// `if (a) if (b) {}`
25-
`${ifStatementWithoutAlternate} > ${ifStatementWithoutAlternate}.consequent`,
26-
]);
11+
const isIfStatementWithoutAlternate = node => node.type === 'IfStatement' && !node.alternate;
2712

2813
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#Table
2914
// Lower precedence than `&&`
@@ -121,19 +106,36 @@ function fix(innerIfStatement, sourceCode) {
121106
}
122107

123108
/** @param {import('eslint').Rule.RuleContext} context */
124-
const create = context => {
125-
const {sourceCode} = context;
126-
127-
return {
128-
[selector](node) {
129-
return {
130-
node,
131-
messageId: MESSAGE_ID,
132-
fix: fix(node, sourceCode),
133-
};
134-
},
135-
};
136-
};
109+
const create = context => ({
110+
IfStatement(ifStatement) {
111+
if (!(
112+
isIfStatementWithoutAlternate(ifStatement)
113+
&& (
114+
// `if (a) { if (b) {} }`
115+
(
116+
ifStatement.parent.type === 'BlockStatement'
117+
&& ifStatement.parent.body.length === 1
118+
&& ifStatement.parent.body[0] === ifStatement
119+
&& isIfStatementWithoutAlternate(ifStatement.parent.parent)
120+
&& ifStatement.parent.parent.consequent === ifStatement.parent
121+
)
122+
// `if (a) if (b) {}`
123+
|| (
124+
isIfStatementWithoutAlternate(ifStatement.parent)
125+
&& ifStatement.parent.consequent === ifStatement
126+
)
127+
)
128+
)) {
129+
return;
130+
}
131+
132+
return {
133+
node: ifStatement,
134+
messageId: MESSAGE_ID,
135+
fix: fix(ifStatement, context.sourceCode),
136+
};
137+
},
138+
});
137139

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

0 commit comments

Comments
 (0)