Skip to content

Commit

Permalink
refactor(minifier): implement array helpers for folding constructor
Browse files Browse the repository at this point in the history
  • Loading branch information
camchenry committed Oct 2, 2024
1 parent 1131f92 commit 5f18f8b
Showing 1 changed file with 14 additions and 17 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -340,16 +340,8 @@ impl<'a> PeepholeSubstituteAlternateSyntax {
}
// `new Array(8)` -> `Array(8)`
else if arg.is_number_literal() {
let mut arguments = Vec::new_in(ctx.ast.allocator);
arguments
.push(ctx.ast.argument_expression((*arg).clone_in(ctx.ast.allocator)));
*expr = ctx.ast.expression_call(
new_expr.span,
new_expr.callee.clone_in(ctx.ast.allocator),
NONE,
arguments,
false,
)
*expr = self.array_constructor_call(&new_expr.arguments, ctx);
self.changed = true;
}
// `new Array(literal)` -> `[literal]`
else if arg.is_literal() {
Expand All @@ -363,13 +355,8 @@ impl<'a> PeepholeSubstituteAlternateSyntax {
}
// `new Array()` -> `Array()`
else {
*expr = ctx.ast.expression_call(
new_expr.span,
new_expr.callee.clone_in(ctx.ast.allocator),
NONE,
new_expr.arguments.clone_in(ctx.ast.allocator),
false,
)
*expr = self.array_constructor_call(&new_expr.arguments, ctx);
self.changed = true;
}
}
}
Expand All @@ -395,6 +382,16 @@ impl<'a> PeepholeSubstituteAlternateSyntax {
}
}
}

/// returns an `Array()` constructor call with zero, one, or more arguments
fn array_constructor_call(
&self,
arguments: &Vec<'a, Argument<'a>>,
ctx: &mut TraverseCtx<'a>,
) -> Expression<'a> {
let callee = ctx.ast.expression_identifier_reference(SPAN, "Array");
ctx.ast.expression_call(SPAN, callee, NONE, arguments.clone_in(ctx.ast.allocator), false)
}
}

/// <https://github.com/google/closure-compiler/blob/master/test/com/google/javascript/jscomp/PeepholeSubstituteAlternateSyntax.java>
Expand Down

0 comments on commit 5f18f8b

Please sign in to comment.