@@ -15,7 +15,7 @@ const isNothing = (node?: T.Node): boolean => {
1515 }
1616} ;
1717
18- const getLocLength = ( loc : T . SourceLocation ) => loc . end . line - loc . start . line + 1 ;
18+ const getLineLength = ( loc : T . SourceLocation ) => loc . end . line - loc . start . line + 1 ;
1919
2020const rule : TSESLint . RuleModule < "noEarlyReturn" | "noConditionalReturn" , [ ] > = {
2121 meta : {
@@ -48,24 +48,26 @@ const rule: TSESLint.RuleModule<"noEarlyReturn" | "noConditionalReturn", []> = {
4848 } ;
4949 const currentFunction = ( ) => functionStack [ functionStack . length - 1 ] ;
5050 const onFunctionEnter = ( node : FunctionNode ) => {
51- const getLastReturn = ( ) => {
52- if ( node . body . type === "BlockStatement" ) {
53- const { length } = node . body . body ;
54- const last = length && node . body . body [ length - 1 ] ;
55- if ( last && last . type === "ReturnStatement" ) {
56- return last ;
57- }
51+ let lastReturn : T . ReturnStatement | undefined ;
52+ if ( node . body . type === "BlockStatement" ) {
53+ const { length } = node . body . body ;
54+ const last = length && node . body . body [ length - 1 ] ;
55+ if ( last && last . type === "ReturnStatement" ) {
56+ lastReturn = last ;
5857 }
59- } ;
60- functionStack . push ( { isComponent : false , lastReturn : getLastReturn ( ) , earlyReturns : [ ] } ) ;
58+ }
59+ functionStack . push ( { isComponent : false , lastReturn, earlyReturns : [ ] } ) ;
6160 } ;
61+
6262 const onFunctionExit = ( node : FunctionNode ) => {
6363 if (
64+ ( node . type === "FunctionDeclaration" && node . id ?. name ?. match ( / ^ [ a - z ] / ) ) ||
6465 node . parent ?. type === "JSXExpressionContainer" // "render props" aren't components
6566 ) {
6667 currentFunction ( ) . isComponent = false ;
6768 }
6869 if ( currentFunction ( ) . isComponent ) {
70+ // Warn on each early return
6971 currentFunction ( ) . earlyReturns . forEach ( ( earlyReturn ) => {
7072 context . report ( {
7173 node : earlyReturn ,
@@ -115,7 +117,7 @@ const rule: TSESLint.RuleModule<"noEarlyReturn" | "noConditionalReturn", []> = {
115117 }
116118 if (
117119 isNothing ( fallback ) ||
118- getLocLength ( consequent . loc ) >= getLocLength ( alternate . loc ) * 1.5
120+ getLineLength ( consequent . loc ) >= getLineLength ( alternate . loc ) * 1.5
119121 ) {
120122 // we have a standard ternary, and the alternate is a bit shorter in LOC than the consequent, which
121123 // should be enough to tell that it's logically a fallback instead of an equal branch.
0 commit comments