Skip to content

Commit

Permalink
refactor(minifier): extract extract_id_or_assign_to_id method (#8822)
Browse files Browse the repository at this point in the history
  • Loading branch information
sapphi-red committed Feb 1, 2025
1 parent 0063318 commit 3abf2f7
Showing 1 changed file with 22 additions and 14 deletions.
36 changes: 22 additions & 14 deletions crates/oxc_minifier/src/peephole/minimize_conditions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1054,28 +1054,18 @@ impl<'a> PeepholeOptimizations {
None
}
};
let is_id_or_assign_to_id = |b: &Expression<'a>| match b {
Expression::Identifier(id) => Some(id.name),
Expression::AssignmentExpression(assign_expr) => {
if assign_expr.operator == AssignmentOperator::Assign {
if let AssignmentTarget::AssignmentTargetIdentifier(id) = &assign_expr.left {
return Some(id.name);
}
}
None
}
_ => None,
};
let (left_value, (left_non_value_expr, left_id_name)) = {
let left_value;
let left_non_value;
if let Some(v) = is_null_or_undefined(&left_binary_expr.left) {
left_value = v;
let left_non_value_id = is_id_or_assign_to_id(&left_binary_expr.right)?;
let left_non_value_id =
Self::extract_id_or_assign_to_id(&left_binary_expr.right)?.name;
left_non_value = (&mut left_binary_expr.right, left_non_value_id);
} else {
left_value = is_null_or_undefined(&left_binary_expr.right)?;
let left_non_value_id = is_id_or_assign_to_id(&left_binary_expr.left)?;
let left_non_value_id =
Self::extract_id_or_assign_to_id(&left_binary_expr.left)?.name;
left_non_value = (&mut left_binary_expr.left, left_non_value_id);
}
(left_value, left_non_value)
Expand Down Expand Up @@ -1112,6 +1102,24 @@ impl<'a> PeepholeOptimizations {
))
}

/// Returns the identifier or the assignment target's identifier of the given expression.
fn extract_id_or_assign_to_id<'b>(
expr: &'b Expression<'a>,
) -> Option<&'b IdentifierReference<'a>> {
match expr {
Expression::Identifier(id) => Some(id),
Expression::AssignmentExpression(assign_expr) => {
if assign_expr.operator == AssignmentOperator::Assign {
if let AssignmentTarget::AssignmentTargetIdentifier(id) = &assign_expr.left {
return Some(id);
}
}
None
}
_ => None,
}
}

/// Compress `a = a || b` to `a ||= b`
///
/// This can only be done for resolved identifiers as this would avoid setting `a` when `a` is truthy.
Expand Down

0 comments on commit 3abf2f7

Please sign in to comment.