Skip to content

Commit

Permalink
feat(minifier): fold object constructor
Browse files Browse the repository at this point in the history
  • Loading branch information
camchenry committed Oct 1, 2024
1 parent a949ecb commit 41d8d1f
Showing 1 changed file with 40 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use oxc_allocator::Vec;
use oxc_ast::ast::*;
use oxc_semantic::IsGlobalReference;
use oxc_span::{GetSpan, SPAN};
use oxc_syntax::{
number::NumberBase,
Expand Down Expand Up @@ -80,6 +82,9 @@ impl<'a> Traverse<'a> for PeepholeSubstituteAlternateSyntax {
if !self.compress_undefined(expr, ctx) {
self.compress_boolean(expr, ctx);
}

self.compress_new_expression(expr, ctx);
self.compress_call_expression(expr, ctx);
}

fn exit_binary_expression(
Expand Down Expand Up @@ -260,6 +265,32 @@ impl<'a> PeepholeSubstituteAlternateSyntax {
self.changed = true;
}
}

fn compress_new_expression(&mut self, expr: &mut Expression<'a>, ctx: &mut TraverseCtx<'a>) {
if let Expression::NewExpression(new_expr) = expr {
// `new Object` -> `{}`
if new_expr.callee.is_global_reference_name("Object", ctx.symbols())
&& new_expr.arguments.is_empty()
{
*expr =
ctx.ast.expression_object(expr.span(), Vec::new_in(ctx.ast.allocator), None);
self.changed = true;
}
}
}

fn compress_call_expression(&mut self, expr: &mut Expression<'a>, ctx: &mut TraverseCtx<'a>) {
if let Expression::CallExpression(call_expr) = expr {
// `Object()` -> `{}`
if call_expr.callee.is_global_reference_name("Object", ctx.symbols())
&& call_expr.arguments.is_empty()
{
*expr =
ctx.ast.expression_object(expr.span(), Vec::new_in(ctx.ast.allocator), None);
self.changed = true;
}
}
}
}

/// <https://github.com/google/closure-compiler/blob/master/test/com/google/javascript/jscomp/PeepholeSubstituteAlternateSyntax.java>
Expand Down Expand Up @@ -302,4 +333,13 @@ mod test {
// shadowd
test_same("(function(undefined) { let x = typeof undefined; })()");
}

#[test]
fn fold_literal_object_constructors() {
test("x = new Object", "x = ({})");
test("x = new Object()", "x = ({})");
test("x = Object()", "x = ({})");

test_same("x = (function f(){function Object(){this.x=4}return new Object();})();");
}
}

0 comments on commit 41d8d1f

Please sign in to comment.