diff --git a/crates/oxc_linter/src/rules/eslint/no_else_return.rs b/crates/oxc_linter/src/rules/eslint/no_else_return.rs index 7b199e8740505..84d7bcd4c4568 100644 --- a/crates/oxc_linter/src/rules/eslint/no_else_return.rs +++ b/crates/oxc_linter/src/rules/eslint/no_else_return.rs @@ -263,8 +263,14 @@ fn left_offset_for_whitespace(ctx: &LintContext, position: u32) -> u32 { return position; } - let chars = ctx.source_text()[..(position as usize)].chars().rev(); - let offset = chars.take_while(|c| c.is_whitespace()).count(); + let mut offset = 0; + for c in ctx.source_text()[..(position as usize)].chars().rev() { + if !c.is_whitespace() { + break; + } + offset += c.len_utf8(); + } + debug_assert!(offset < u32::MAX as usize); offset as u32 } @@ -423,6 +429,7 @@ fn test() { ]; let fail = vec![ + ("if(0)return;else r", None), ("function foo1() { if (true) { return x; } else { return y; } }", None), ("function foo2() { if (true) { var x = bar; return x; } else { var y = baz; return y; } }", None), ("function foo3() { if (true) return x; else return y; }", None), @@ -514,6 +521,7 @@ fn test() { ]; let fix = vec![ + ("if(0)return;else r", "if(0)return; r", None), ("function foo1() { if (true) { return x; } else { return y; } }", "function foo1() { if (true) { return x; } return y; }", None), ("function foo1() { if(true){ return x; }else{ return y; } }", "function foo1() { if(true){ return x; } return y; }", None), ("function foo2() { if (true) { var x = bar; return x; } else { var y = baz; return y; } }", "function foo2() { if (true) { var x = bar; return x; } var y = baz; return y; }", None), diff --git a/crates/oxc_linter/src/snapshots/no_else_return.snap b/crates/oxc_linter/src/snapshots/no_else_return.snap index 5ad909557eefd..f088ccba1dce7 100644 --- a/crates/oxc_linter/src/snapshots/no_else_return.snap +++ b/crates/oxc_linter/src/snapshots/no_else_return.snap @@ -1,6 +1,15 @@ --- source: crates/oxc_linter/src/tester.rs --- + ⚠ eslint(no-else-return): Unnecessary 'else' after 'return'. + ╭─[no_else_return.tsx:1:6] + 1 │ if(0)return;else r + · ───┬─────┬── + · │ ╰── Making this `else` block unnecessary. + · ╰── This consequent block always returns, + ╰──── + help: Remove the `else` block, moving its contents outside of the `if` statement. + ⚠ eslint(no-else-return): Unnecessary 'else' after 'return'. ╭─[no_else_return.tsx:1:31] 1 │ function foo1() { if (true) { return x; } else { return y; } }