Skip to content

Commit 263f051

Browse files
committed
feat(minifier): remove typeof guarded global access expressions
refs #12981
1 parent 7346099 commit 263f051

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

crates/oxc_minifier/src/peephole/remove_unused_expression.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,9 @@ impl<'a> PeepholeOptimizations {
6565
}
6666

6767
fn remove_unused_logical_expr(e: &mut Expression<'a>, ctx: &mut Ctx<'a, '_>) -> bool {
68+
if !e.may_have_side_effects(ctx) {
69+
return true;
70+
}
6871
let Expression::LogicalExpression(logical_expr) = e else { return false };
6972
if !logical_expr.operator.is_coalesce() {
7073
Self::minimize_expression_in_boolean_context(&mut logical_expr.left, ctx);
@@ -378,6 +381,9 @@ impl<'a> PeepholeOptimizations {
378381
}
379382

380383
fn remove_unused_conditional_expr(e: &mut Expression<'a>, ctx: &mut Ctx<'a, '_>) -> bool {
384+
if !e.may_have_side_effects(ctx) {
385+
return true;
386+
}
381387
let Expression::ConditionalExpression(conditional_expr) = e else {
382388
return false;
383389
};
@@ -884,6 +890,11 @@ mod test {
884890
test_same("v = a == null && (a = b)");
885891
test_same("v = a != null || (a = b)");
886892
test("void (x == null && y)", "x ?? y");
893+
894+
test("typeof x != 'undefined' && x", "");
895+
test("typeof x == 'undefined' || x", "");
896+
test("typeof x < 'u' && x", "");
897+
test("typeof x > 'u' || x", "");
887898
}
888899

889900
#[expect(clippy::literal_string_with_formatting_args)]
@@ -925,6 +936,11 @@ mod test {
925936
test("foo() ? 1 : bar()", "foo() || bar()");
926937
test("foo() ? bar() : 2", "foo() && bar()");
927938
test_same("foo() ? bar() : baz()");
939+
940+
test("typeof x == 'undefined' ? 0 : x", "");
941+
test("typeof x != 'undefined' ? x : 0", "");
942+
test("typeof x > 'u' ? 0 : x", "");
943+
test("typeof x < 'u' ? x : 0", "");
928944
}
929945

930946
#[test]

0 commit comments

Comments
 (0)