Skip to content

Commit

Permalink
feat(minifier): merge single var declarations without init into for-of (
Browse files Browse the repository at this point in the history
#8813)

for-of version of #8812.
  • Loading branch information
sapphi-red committed Jan 31, 2025
1 parent 99b47ed commit f02d9e9
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,6 @@ mod test {
}

#[test]
#[ignore]
fn test_for_of() {
test("var a; for (a of b) foo()", "for (var a of b) foo()");
test_same("a = 0; for (a of b) foo()");
Expand Down
32 changes: 32 additions & 0 deletions crates/oxc_minifier/src/peephole/minimize_statements.rs
Original file line number Diff line number Diff line change
Expand Up @@ -407,6 +407,38 @@ impl<'a> PeepholeOptimizations {
}
result.push(Statement::ForInStatement(for_in_stmt));
}
Statement::ForOfStatement(mut for_of_stmt) => {
// "var a; for (a of b) c" => "for (var a of b) c"
if let Some(Statement::VariableDeclaration(prev_var_decl)) = result.last_mut() {
if let ForStatementLeft::AssignmentTargetIdentifier(id) = &for_of_stmt.left {
let prev_var_decl_no_init_item = {
if prev_var_decl.kind.is_var()
&& prev_var_decl.declarations.len() == 1
&& prev_var_decl.declarations[0].init.is_none()
{
Some(&prev_var_decl.declarations[0])
} else {
None
}
};
if let Some(prev_var_decl_item) = prev_var_decl_no_init_item {
if let BindingPatternKind::BindingIdentifier(decl_id) =
&prev_var_decl_item.id.kind
{
if id.name == decl_id.name {
for_of_stmt.left =
ForStatementLeft::VariableDeclaration(ctx.ast.alloc(
ctx.ast.move_variable_declaration(prev_var_decl),
));
result.pop();
self.mark_current_function_as_changed();
}
}
}
}
}
result.push(Statement::ForOfStatement(for_of_stmt));
}
stmt => result.push(stmt),
}
}
Expand Down

0 comments on commit f02d9e9

Please sign in to comment.