Skip to content

Commit

Permalink
perf(plugin/replace): expand_typeof_replacements avoid temporary ve…
Browse files Browse the repository at this point in the history
…cs (#2321)

### Description

Pure refactor. Avoid temporary `Vec`s in `expand_typeof_replacements`.

Also avoid a pointless conversion of `Vec` to `HashMap` when that
`HashMap` is immediately converted back to an iterator in the caller
anyway.
  • Loading branch information
overlookmotel authored Sep 25, 2024
1 parent 22b43cd commit 84cb2a2
Showing 1 changed file with 19 additions and 23 deletions.
42 changes: 19 additions & 23 deletions crates/rolldown_plugin_replace/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,35 +9,31 @@ static OBJECT_RE: LazyLock<Regex> = LazyLock::new(|| {

pub(crate) fn expand_typeof_replacements(
values: &HashMap<String, String>,
) -> HashMap<String, String> {
) -> Vec<(String, String)> {
let mut replacements: Vec<(String, String)> = Vec::new();

for key in values.keys() {
if OBJECT_RE.is_match(key) {
let capture_vec: Vec<&str> = key.split('.').collect::<Vec<&str>>();

let capture_arr = capture_vec.as_slice();

let replaces: Vec<(String, String)> = capture_arr[0..capture_arr.len() - 1]
.iter()
.flat_map(|x| {
vec![
(format!("typeof {} ===", *x), "\"object\" ===".to_string()),
(format!("typeof {}===", *x), "\"object\"===".to_string()),
(format!("typeof {} !==", *x), "\"object\" !==".to_string()),
(format!("typeof {}!==", *x), "\"object\"!==".to_string()),
(format!("typeof {} ==", *x), "\"object\" ===".to_string()),
(format!("typeof {}==", *x), "\"object\"===".to_string()),
(format!("typeof {}!=", *x), "\"object\"!==".to_string()),
(format!("typeof {} !=", *x), "\"object\" !==".to_string()),
]
})
.collect();
replacements.extend(replaces);
// Skip last part
let mut parts = key.split('.');
let mut part = parts.next().unwrap();
for next in parts {
replacements.extend([
(format!("typeof {part} ==="), "\"object\" ===".to_string()),
(format!("typeof {part}==="), "\"object\"===".to_string()),
(format!("typeof {part} !=="), "\"object\" !==".to_string()),
(format!("typeof {part}!=="), "\"object\"!==".to_string()),
(format!("typeof {part} =="), "\"object\" ===".to_string()),
(format!("typeof {part}=="), "\"object\"===".to_string()),
(format!("typeof {part}!="), "\"object\"!==".to_string()),
(format!("typeof {part} !="), "\"object\" !==".to_string()),
]);
part = next;
}
};
}

HashMap::from_iter(replacements)
replacements
}

#[cfg(test)]
Expand All @@ -48,7 +44,7 @@ mod tests {

fn run_test(keys: &[&str], expected: &[(&str, &str)]) {
let map = keys.iter().copied().map(|key| (key.to_string(), "x".to_string())).collect();
let result = expand_typeof_replacements(&map);
let result = expand_typeof_replacements(&map).into_iter().collect::<HashMap<_, _>>();
let expected = expected
.iter()
.copied()
Expand Down

0 comments on commit 84cb2a2

Please sign in to comment.