chore: optimize rust program, add tests

This commit is contained in:
Ivan R. 2024-02-07 21:46:21 +05:00
parent f41a9f0827
commit 48587158b2
No known key found for this signature in database
GPG key ID: 56C7BAAE859B302C
2 changed files with 57 additions and 29 deletions

View file

@ -0,0 +1,57 @@
use std::collections::HashSet;
fn process_local_part(s: &str) -> String {
match s.find('+') {
Some(plus_index) => &s[0..plus_index],
None => s,
}
.replace('.', "")
}
#[cfg(test)]
mod process_local_part_tests {
use super::process_local_part;
#[test]
fn processing_works() {
let result = process_local_part("a.b+c");
assert_eq!(result, "ab");
}
#[test]
fn processing_without_plus_works() {
let result = process_local_part("a.b");
assert_eq!(result, "ab");
}
}
pub fn num_unique_emails(emails: Vec<String>) -> i32 {
let mut unique_emails = HashSet::new();
for email in emails.iter() {
let parts: Vec<&str> = email.split('@').collect();
unique_emails.insert(format!("{}@{}", process_local_part(parts[0]), parts[1]));
}
unique_emails.len() as i32
}
#[cfg(test)]
mod num_unique_emails_tests {
use super::num_unique_emails;
#[test]
fn num_unique_emails_is_correct() {
let result = num_unique_emails(
[
"test.email+alex@leetcode.com",
"test.e.mail+bob.cathy@leetcode.com",
"testemail+david@lee.tcode.com",
]
.iter()
.map(|s| s.to_string())
.collect(),
);
assert_eq!(result, 2)
}
}

View file

@ -1,29 +0,0 @@
use std::collections::HashSet;
pub fn num_unique_emails(emails: Vec<String>) -> i32 {
let mut unique_emails = HashSet::new();
for email in emails.iter() {
let mut parts: Vec<String> = email
.split("@")
.map(|s| s.to_string())
.collect();
parts[0] = parts[0]
.replace(".", "")
.split("+")
.collect::<Vec<&str>>()[0]
.to_string();
unique_emails.insert(format!("{}@{}", parts[0], parts[1]));
}
unique_emails.len() as i32
}
fn main() {
let inp: Vec<String> = vec![
"test.email+alex@leetcode.com",
"test.e.mail+bob.cathy@leetcode.com",
"testemail+david@lee.tcode.com",
].iter().map(|s| s.to_string()).collect();
println!("{}", num_unique_emails(inp));
}