Skip to content

Instantly share code, notes, and snippets.

@killercup
Last active October 5, 2017 18:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save killercup/28b552f6378c4a1ea1daeb14bb4075b4 to your computer and use it in GitHub Desktop.
Save killercup/28b552f6378c4a1ea1daeb14bb4075b4 to your computer and use it in GitHub Desktop.
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