Saturday 4 September 2021

rust sample code: splitting array of string on comma and space

 

I'm keeping this code snippet because it isn't going to make it into dust and I think it's impressive.


/**
* Takes an Option<iterable of string> and returns a HashSet of strings that have been
* split by comma and whitespace
*/
fn clean_input<'a, I>(cmd_line_arg: Option<I>) -> HashSet<&'a str>
where
I: Iterator<Item = &'a str>,
{
match cmd_line_arg {
Some(aa) => aa
.map(|a| {
a.split_whitespace()
.map(|bb| bb.split(','))
.flatten()
.collect::<Vec<&str>>()
})
.flatten()
.filter(|a| !a.is_empty())
.collect::<HashSet<&str>>(),
None => HashSet::new(),
}
}


No comments:

Post a Comment