Skip to content

Commit

Permalink
refactor(transformer): use Option::get_or_insert_with (#6299)
Browse files Browse the repository at this point in the history
`Option::get_or_insert_with` is designed for use case where you want to fill an `Option` if it's `None`, and get the contents either way. Use it in transformer where borrow checker allows.
  • Loading branch information
overlookmotel committed Oct 6, 2024
1 parent 1a5f293 commit 7f5a94b
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 15 deletions.
9 changes: 4 additions & 5 deletions crates/oxc_transformer/src/plugins/inject_global_variables.rs
Original file line number Diff line number Diff line change
Expand Up @@ -236,13 +236,12 @@ impl<'a> InjectGlobalVariables<'a> {
if ReplaceGlobalDefines::is_dot_define(ctx.symbols(), dot_define, member) {
// If this is first replacement made for this dot define,
// create `Atom` for replacement, and record in `replaced_dot_defines`
if value_atom.is_none() {
*value_atom = Some(self.ast.atom(dot_define.value.as_str()));

let value_atom = value_atom.get_or_insert_with(|| {
self.replaced_dot_defines
.push((dot_define.parts[0].clone(), dot_define.value.clone()));
}
let value_atom = value_atom.as_ref().unwrap().clone();
self.ast.atom(dot_define.value.as_str())
});
let value_atom = value_atom.clone();

let value = self.ast.expression_identifier_reference(SPAN, value_atom);
*expr = value;
Expand Down
16 changes: 6 additions & 10 deletions crates/oxc_transformer/src/react/jsx_source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,10 +77,9 @@ impl<'a, 'ctx> Traverse<'a> for ReactJsxSource<'a, 'ctx> {

impl<'a, 'ctx> ReactJsxSource<'a, 'ctx> {
pub fn get_line_column(&mut self, offset: u32) -> (usize, usize) {
if self.source_rope.is_none() {
self.source_rope = Some(Rope::from_str(self.ctx.source_text));
}
get_line_column(self.source_rope.as_ref().unwrap(), offset, self.ctx.source_text)
let source_rope =
self.source_rope.get_or_insert_with(|| Rope::from_str(self.ctx.source_text));
get_line_column(source_rope, offset, self.ctx.source_text)
}

pub fn get_object_property_kind_for_jsx_plugin(
Expand Down Expand Up @@ -221,11 +220,8 @@ impl<'a, 'ctx> ReactJsxSource<'a, 'ctx> {
}

fn get_filename_var(&mut self, ctx: &mut TraverseCtx<'a>) -> &BoundIdentifier<'a> {
if self.filename_var.is_none() {
self.filename_var = Some(
ctx.generate_uid_in_root_scope(FILE_NAME_VAR, SymbolFlags::FunctionScopedVariable),
);
}
self.filename_var.as_ref().unwrap()
self.filename_var.get_or_insert_with(|| {
ctx.generate_uid_in_root_scope(FILE_NAME_VAR, SymbolFlags::FunctionScopedVariable)
})
}
}

0 comments on commit 7f5a94b

Please sign in to comment.