Last active
October 5, 2017 18:16
-
-
Save killercup/28b552f6378c4a1ea1daeb14bb4075b4 to your computer and use it in GitHub Desktop.
Glorious `join with and` code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![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