summaryrefslogtreecommitdiff
path: root/backend/app/src/utils/find_by_id_or.rs
blob: f5add30e3e06a44e7bb24d7822f7eb0e778dd429 (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
pub fn find_by_id_or<Id: PartialEq, Val: Copy>(
    arr: &[(Id, Option<Val>)],
    id: Id,
    default: Val,
) -> Val {
    arr.iter()
        .find(|(elem_id, _)| *elem_id == id)
        .map_or(default, |row| match row {
            (_, Some(quantity)) => *quantity,
            (_, _) => default,
        })
}

#[cfg(test)]
mod test {
    use super::find_by_id_or;

    #[test]
    fn when_no_elements_then_return_default() {
        let arr = [];

        let result = find_by_id_or(&arr, 1, 42);

        assert_eq!(result, 42);
    }

    #[test]
    fn when_id_not_in_elements_then_return_default() {
        let arr = [(0, Some(100)), (2, Some(200))];

        let result = find_by_id_or(&arr, 1, 42);

        assert_eq!(result, 42);
    }

    #[test]
    fn when_value_is_none_then_return_default() {
        let arr = [(1, None)];

        let result = find_by_id_or(&arr, 1, 42);

        assert_eq!(result, 42);
    }

    #[test]
    fn when_value_is_some_then_return_value() {
        let arr = [(1, Some(67))];

        let result = find_by_id_or(&arr, 1, 42);

        assert_eq!(result, 67);
    }
}