@@ -42,27 +42,25 @@ export const rule: Rule.RuleModule = {
4242 returnsBoolean ( node . consequent ) &&
4343 alternateReturnsBoolean ( node )
4444 ) {
45+ const suggestions = getSuggestion ( node , parent ) ;
4546 context . report ( {
4647 messageId : 'replaceIfThenElseByReturn' ,
4748 node,
48- suggest : getSuggestion ( node , parent ) ,
49+ ... ( suggestions . length > 0 ? { suggest : suggestions } : { } ) ,
4950 } ) ;
5051 }
5152 } ,
5253 } ;
5354
5455 function getSuggestion ( ifStmt : estree . IfStatement , parent : estree . Node ) {
56+ const replacementRange = getReplacementRange ( ifStmt , parent ) ;
57+ if ( replacementRange === null || hasCommentsInRange ( replacementRange ) ) {
58+ return [ ] ;
59+ }
5560 const getFix = ( condition : string ) => {
5661 return ( fixer : Rule . RuleFixer ) => {
5762 const singleReturn = `return ${ condition } ;` ;
58- if ( ifStmt . alternate ) {
59- return fixer . replaceText ( ifStmt , singleReturn ) ;
60- } else {
61- const ifStmtIndex = ( parent as estree . BlockStatement ) . body . indexOf ( ifStmt ) ;
62- const returnStmt = ( parent as estree . BlockStatement ) . body [ ifStmtIndex + 1 ] ;
63- const range : [ number , number ] = [ ifStmt . range ! [ 0 ] , returnStmt . range ! [ 1 ] ] ;
64- return fixer . replaceTextRange ( range , singleReturn ) ;
65- }
63+ return fixer . replaceTextRange ( replacementRange , singleReturn ) ;
6664 } ;
6765 } ;
6866 const shouldNegate = isReturningFalse ( ifStmt . consequent ) ;
@@ -80,9 +78,41 @@ export const rule: Rule.RuleModule = {
8078 return [ { messageId : 'suggest' , fix : getFix ( testText ) } ] ;
8179 }
8280 }
81+
82+ function hasCommentsInRange ( range : [ number , number ] ) : boolean {
83+ return context . sourceCode . getAllComments ( ) . some ( comment => {
84+ const commentRange = comment . range ;
85+ return (
86+ commentRange !== undefined && commentRange [ 0 ] >= range [ 0 ] && commentRange [ 1 ] <= range [ 1 ]
87+ ) ;
88+ } ) ;
89+ }
8390 } ,
8491} ;
8592
93+ function getReplacementRange (
94+ ifStmt : estree . IfStatement ,
95+ parent : estree . Node ,
96+ ) : [ number , number ] | null {
97+ const ifStmtRange = ifStmt . range ;
98+ if ( ifStmtRange === undefined ) {
99+ return null ;
100+ }
101+
102+ if ( ifStmt . alternate || parent . type !== 'BlockStatement' ) {
103+ return ifStmtRange ;
104+ }
105+
106+ const ifStmtIndex = parent . body . indexOf ( ifStmt ) ;
107+ const returnStmt = parent . body [ ifStmtIndex + 1 ] ;
108+ const returnStmtRange = returnStmt ?. range ;
109+ if ( returnStmtRange === undefined ) {
110+ return null ;
111+ }
112+
113+ return [ ifStmtRange [ 0 ] , returnStmtRange [ 1 ] ] ;
114+ }
115+
86116function isBlockReturningBooleanLiteral ( statement : estree . Statement ) {
87117 return (
88118 statement . type === 'BlockStatement' &&
0 commit comments