refactor(transformer): use Option::get_or_insert_with (#6299)

`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.
This commit is contained in:
overlookmotel 2024-10-06 00:51:27 +00:00
parent 1a5f293d9b
commit 7f5a94b902
2 changed files with 10 additions and 15 deletions

View file

@ -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;

View file

@ -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(
@ -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)
})
}
}