rtools/
apply.rs

1pub trait Apply<T> {
2    fn apply(self, action: impl FnMut(T));
3    fn apply2<U, Second: IntoIterator<Item = U>>(self, second: Second, action: impl FnMut(T, U));
4}
5
6impl<T, I: IntoIterator<Item = T>> Apply<T> for I {
7    fn apply(self, mut action: impl FnMut(T)) {
8        for item in self {
9            action(item);
10        }
11    }
12
13    fn apply2<U, Second: IntoIterator<Item = U>>(self, second: Second, mut action: impl FnMut(T, U)) {
14        for (item, second) in self.into_iter().zip(second) {
15            action(item, second);
16        }
17    }
18}
19
20#[cfg(test)]
21mod test {
22    use crate::apply::Apply;
23
24    #[test]
25    fn apply_arr() {
26        let mut ve = vec![];
27        [1, 2, 3, 4, 5].apply(|a| {
28            ve.push(a);
29        });
30        assert_eq!(&ve, &[1, 2, 3, 4, 5]);
31    }
32
33    #[test]
34    fn apply_tuple() {
35        let mut num = vec![];
36        let mut ch = vec![];
37        [(1, '5'), (2, '4'), (3, '3'), (4, '2'), (5, '1')].apply(|(n, c)| {
38            num.push(n);
39            ch.push(c.clone());
40        });
41        assert_eq!(&num, &[1, 2, 3, 4, 5]);
42        assert_eq!(&ch, &['5', '4', '3', '2', '1']);
43    }
44
45    #[test]
46    fn apply2_arr() {
47        let mut num = vec![];
48        let mut ch = vec![];
49        [1, 2, 3, 4, 5].apply2(['5', '4', '3', '2', '1'], |n, c| {
50            num.push(n);
51            ch.push(c);
52        });
53        assert_eq!(&num, &[1, 2, 3, 4, 5]);
54        assert_eq!(&ch, &['5', '4', '3', '2', '1']);
55    }
56}