Skip to content

Instantly share code, notes, and snippets.

@killercup
Last active Oct 5, 2017
Embed
What would you like to do?
Glorious `join with and` code
#![feature(slice_patterns)]
fn join_with_and(xs: &[&str]) -> String {
match xs.split_last() {
None => String::new(),
Some((last, &[])) => last.to_string(),
Some((last, &[first])) => format!("{} and {}", first, last),
Some((last, beginning)) => format!("{}, and {}", beginning.join(", "), last),
}
}
#[test]
fn works() {
assert_eq!(join_with_and(&[]), "".to_string());
assert_eq!(join_with_and(&["foo"]), "foo".to_string());
assert_eq!(join_with_and(&["foo", "bar"]), "foo and bar".to_string());
assert_eq!(
join_with_and(&["twitter", "reddit", "hackernews"]),
"twitter, reddit, and hackernews".to_string()
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment