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
pub trait Apply<T> {
    fn apply(self, action: impl FnMut(T));
    fn apply2<U, Second: IntoIterator<Item = U>>(self, second: Second, action: impl FnMut(T, U));
}

impl<T, I: IntoIterator<Item = T>> Apply<T> for I {
    fn apply(self, mut action: impl FnMut(T)) {
        for item in self.into_iter() {
            action(item)
        }
    }

    fn apply2<U, Second: IntoIterator<Item = U>>(self, second: Second, mut action: impl FnMut(T, U)) {
        for (item, second) in self.into_iter().zip(second) {
            action(item, second);
        }
    }
}

#[cfg(test)]
mod test {
    use crate::apply::Apply;

    #[test]
    fn apply_arr() {
        let mut ve = vec![];
        [1, 2, 3, 4, 5].apply(|a| {
            ve.push(a);
        });
        assert_eq!(&ve, &[1, 2, 3, 4, 5]);
    }

    #[test]
    fn apply_tuple() {
        let mut num = vec![];
        let mut ch = vec![];
        [(1, '5'), (2, '4'), (3, '3'), (4, '2'), (5, '1')].apply(|(n, c)| {
            num.push(n);
            ch.push(c.clone());
        });
        assert_eq!(&num, &[1, 2, 3, 4, 5]);
        assert_eq!(&ch, &['5', '4', '3', '2', '1']);
    }

    #[test]
    fn apply2_arr() {
        let mut num = vec![];
        let mut ch = vec![];
        [1, 2, 3, 4, 5].apply2(['5', '4', '3', '2', '1'], |n, c| {
            num.push(n);
            ch.push(c);
        });
        assert_eq!(&num, &[1, 2, 3, 4, 5]);
        assert_eq!(&ch, &['5', '4', '3', '2', '1']);
    }
}