summaryrefslogtreecommitdiff
path: root/learn_1/src/main.rs
blob: 0d8181f1057db165987c7e2fba0fad1420cdabb4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
struct Inventory {
    items: Vec<String>,
}

impl Inventory {
    // `new` creates a new Inventory instance.
    pub fn new() -> Self {
        Self{ items: Vec::new() }
    }

    // `add` inserts a new item.
    pub fn add(&mut self, item: String) {
        self.items.push(item)
    }

    // `contains` returns true if `item` is in `self.items`.
    pub fn contains(&self, item: &str) -> bool {
        self.items.iter().any(|x| x == item)
    }

    // `remove` removes `item` from `self.items` if present.
    pub fn remove(&mut self, item: &str) -> Option<String> {
        let index: usize = self.items.iter().position(|x| x.as_str() == item)?;
        Some(self.items.remove(index))
    }

    // `list` returns a slice of the inventory items.
    pub fn list(&self) -> &[String] {
        self.items.as_slice()
    }
}

fn main() {
    ()
}

#[cfg(test)]
mod tests {
    use crate::*;

    #[test]
    fn test_new() {
        let inventory = Inventory::new();
        assert_eq!(inventory.items.len(), 0 as usize);
    }

    #[test]
    fn test_add() {
        let mut inventory = Inventory::new();
        inventory.add(String::from("a"));
        assert_eq!(inventory.contains(&String::from("a")), true);
    }
    
    #[test]
    fn test_contains() {
        let mut inventory = Inventory::new();
        inventory.add(String::from("a"));
        assert_eq!(inventory.contains(&String::from("a")), true);
        assert_eq!(inventory.contains(&String::from("b")), false);
    }

    #[test]
    fn test_remove() {
        let mut inventory = Inventory::new();
        inventory.add(String::from("a"));
        let removed = inventory.remove(&String::from("a"));
        assert!(removed.is_some_and(|x| x == String::from("a")));
        let miss = inventory.remove(&String::from("b"));
        assert!(miss.is_none());

        inventory.add(String::from("a"));
        inventory.add(String::from("b"));
        inventory.add(String::from("a"));
        assert_eq!(inventory.list(), &["a","b","a"]);
        let removed2 = inventory.remove(&String::from("a"));
        assert!(removed2.is_some_and(|x| x == String::from("a")));
        assert_eq!(inventory.list(), &["b","a"]);
    }

    #[test]
    fn test_list() {
        let mut inventory = Inventory::new();
        inventory.add(String::from("a"));
        assert_eq!(inventory.list(), &[String::from("a")]);
    }
}