#[must_use]
pub fn listed<S: AsRef<str>>(items: &[S]) -> String {
match items {
[] => String::new(),
[one] => one.as_ref().to_owned(),
[rest @ .., last] => format!(
"{} and {}",
rest.iter()
.map(AsRef::as_ref)
.collect::<Vec<_>>()
.join(", "),
last.as_ref()
),
}
}
#[cfg(test)]
mod tests {
use super::listed;
#[test]
fn lists_read_as_a_sentence() {
assert_eq!(listed::<&str>(&[]), "");
assert_eq!(listed(&["a"]), "a");
assert_eq!(listed(&["a", "b"]), "a and b");
assert_eq!(listed(&["a", "b", "c"]), "a, b and c");
}
}