Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions crates/oxc_minifier/src/peephole/fold_constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -467,9 +467,9 @@ impl<'a> PeepholeOptimizations {
}

// remove useless `+ ""` (e.g. `typeof foo + ""` -> `typeof foo`)
if left_expr.is_specific_string_literal("") && right_expr.value_type(&ctx).is_string() {
if Self::evaluates_to_empty_string(left_expr) && right_expr.value_type(&ctx).is_string() {
return Some(ctx.ast.move_expression(right_expr));
} else if right_expr.is_specific_string_literal("")
} else if Self::evaluates_to_empty_string(right_expr)
&& left_expr.value_type(&ctx).is_string()
{
return Some(ctx.ast.move_expression(left_expr));
Expand All @@ -478,6 +478,14 @@ impl<'a> PeepholeOptimizations {
None
}

fn evaluates_to_empty_string(e: &Expression<'a>) -> bool {
match e {
Expression::StringLiteral(s) => s.value.is_empty(),
Expression::ArrayExpression(a) => a.elements.is_empty(),
_ => false,
}
}

fn try_fold_left_child_op(
e: &mut BinaryExpression<'a>,
ctx: Ctx<'a, '_>,
Expand Down Expand Up @@ -1839,6 +1847,10 @@ mod test {
fold_same("typeof foo + '123'");
fold("typeof foo + ''", "typeof foo");
fold("'' + typeof foo", "typeof foo");
fold("typeof foo + ``", "typeof foo");
fold("`` + typeof foo", "typeof foo");
fold("typeof foo + []", "typeof foo");
fold("[] + typeof foo", "typeof foo");
fold("(foo ? 'a' : 'b') + ''", "foo ? 'a' : 'b'");
fold_same("typeof foo - ''");
}
Expand Down
4 changes: 2 additions & 2 deletions crates/oxc_minifier/tests/peephole/esbuild.rs
Original file line number Diff line number Diff line change
Expand Up @@ -315,8 +315,8 @@ fn js_parser_test() {
test("a = typeof b + ''", "a = typeof b;");
test("a = [] + `${b}`", "a = `${b}`;");
test("a = `${b}` + []", "a = `${b}`;");
// test("a = [] + typeof b", "a = typeof b;");
// test("a = typeof b + []", "a = typeof b;");
test("a = [] + typeof b", "a = typeof b;");
test("a = typeof b + []", "a = typeof b;");
test("a = [b] + `${b}`", "a = [b] + `${b}`;");
test("a = `${b}` + [b]", "a = `${b}` + [b];");
test("a = {} + `${b}`", "a = `[object Object]${b}`;");
Expand Down
Loading