Skip to main content

speccoder_core/
words.rs

1//! Lists in a sentence.
2
3/// `a`, `a and b`, `a, b and c`.
4#[must_use]
5pub fn listed<S: AsRef<str>>(items: &[S]) -> String {
6    match items {
7        [] => String::new(),
8        [one] => one.as_ref().to_owned(),
9        [rest @ .., last] => format!(
10            "{} and {}",
11            rest.iter()
12                .map(AsRef::as_ref)
13                .collect::<Vec<_>>()
14                .join(", "),
15            last.as_ref()
16        ),
17    }
18}
19
20#[cfg(test)]
21mod tests {
22    use super::listed;
23
24    #[test]
25    fn lists_read_as_a_sentence() {
26        assert_eq!(listed::<&str>(&[]), "");
27        assert_eq!(listed(&["a"]), "a");
28        assert_eq!(listed(&["a", "b"]), "a and b");
29        assert_eq!(listed(&["a", "b", "c"]), "a, b and c");
30    }
31}