teljari/
lib.rs

1/// Join vector of strings to a human-readable string with conjunction.
2///
3/// 
4/// # Examples
5/// 
6/// ```
7/// use teljari::join_with_conj;
8/// 
9/// let list: Vec<&str> = vec!("Me", "Myself", "I");
10/// let conj: &str = "and";
11/// let result = join_with_conj(&list, &conj);
12/// 
13/// assert_eq!(result, "Me, Myself and I");
14/// ```
15pub fn join_with_conj(list: &[&str], conj: &str) -> String {
16    if list.is_empty() { panic!("Array should not be empty"); }
17    if list.len() == 1 { return String::from(list[0]); }
18
19    let first_ones: String = list[0..list.len() - 1].join(", ");
20    let last: &str = list.last().unwrap();
21
22    return format!("{} {} {}", first_ones, conj, last);
23}
24
25#[cfg(test)]
26mod tests {
27    use super::*;
28
29    #[test]
30    #[should_panic(expected = "Array should not be empty")]
31    fn panics_on_empty_array() {
32        let list: Vec<&str> = Vec::new();
33        let conj: &str = "whatever";
34
35        join_with_conj(&list, conj);
36    }
37
38    #[test]
39    fn does_not_add_conjunction_to_one_member_list() {
40        let list: Vec<&str> = vec!("Finnish");
41        let conj: &str = "and (which should not be printed)";
42        let expected = "Finnish";
43        let result = join_with_conj(&list, conj);
44        assert_eq!(result, expected);
45    }
46
47    #[test]
48    fn does_not_add_commas_to_two_member_list() {
49        let list: Vec<&str> = vec!("Finnish", "Karelian");
50        let conj: &str = "or";
51        let expected = "Finnish or Karelian";
52        let result = join_with_conj(&list, conj);
53        assert_eq!(result, expected);
54    }
55
56    #[test]
57    fn joins_with_and_conjunction() {
58        let list: Vec<&str> = vec!("Finnish", "Swedish", "Norwegian", "Danish");
59        let conj: &str = "and";
60        let expected = "Finnish, Swedish, Norwegian and Danish";
61        let result = join_with_conj(&list, conj);
62        assert_eq!(result, expected);
63    }
64
65    #[test]
66    fn joins_with_or_conjunction() {
67        let list: Vec<&str> = vec!("Finnish", "Swedish", "Norwegian", "Danish");
68        let conj: &str = "or worse";
69        let expected = "Finnish, Swedish, Norwegian or worse Danish";
70        let result = join_with_conj(&list, conj);
71        assert_eq!(result, expected);
72    }
73}