import type { TSESTree , TSESLint } from '@typescript-eslint/experimental-utils' ; import { isReturnStatement , isBlockStatement , isBooleanLiteral , isIfStatement , } from '../utils/nodes' ; import docsUrl from '../utils/docs-url' ; const rule = { meta : { messages : { replaceIfThenElseByReturn : 'Replace this if-then-else statement by a single return statement.' , } , schema : [ ] , type : 'suggestion' , docs : { description : 'Return of boolean expressions should not be wrapped into an "if-then-else" statement' , recommended : 'error' , url : docsUrl ( __filename ) , } , } , create ( context ) { return { IfStatement ( node ) { const ifStmt = node as TSESTree . IfStatement ; if ( ! isIfStatement ( ifStmt . parent ) && returnsBoolean ( ifStmt . alternate || undefined ) && returnsBoolean ( ifStmt . consequent ) ) { context . report ( { messageId : 'replaceIfThenElseByReturn' , node : ifStmt , } ) ; } } , } ; function returnsBoolean ( statement ) { return ( statement !== undefined && ( isBlockReturningBooleanLiteral ( statement ) || isSimpleReturnBooleanLiteral ( statement ) ) ) ; } function isBlockReturningBooleanLiteral ( statement ) { return ( isBlockStatement ( statement ) && statement . body . length === 1 && isSimpleReturnBooleanLiteral ( statement . body [ 0 ] ) ) ; } function isSimpleReturnBooleanLiteral ( statement ) { return isReturnStatement ( statement ) && isBooleanLiteral ( statement . argument || undefined ) ; } } , } ; export = rule ;