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
/// Reduces collection to a value which is the accumulated result of running each element in collection thru iteratee,
/// where each successive invocation is supplied the return value of the previous.
///
/// * accumulator function signature: ```fn(agg: U, item: T, index: usize) -> U```
///
/// # Arguments
///
/// * `collection` - The collection to iterate over.
///
/// * `accumulator` - The function invoked per iteration.
///
/// * `initial` - The initial value.
///
///
/// # Returns
///
/// Returns the accumulated value.
///
/// # Examples
///
/// ```
/// use rufl::collection;
///
/// assert_eq!(15, collection::reduce(&vec![1, 2, 3, 4, 5], |x: &i32, y: &i32, i: usize| { x + y }, 0));
///
/// assert_eq!(120, collection::reduce(&vec![1, 2, 3, 4, 5], |x: &i32, y: &i32, i: usize| { x * y }, 1));
///
/// ```
pub fn reduce<C: AsRef<[T]>, T, U>(
collection: &C,
accumulator: impl Fn(&U, &T, usize) -> U,
initial: U,
) -> U {
let mut result = initial;
let vector = collection.as_ref();
for (index, item) in vector.iter().enumerate() {
result = accumulator(&result, item, index)
}
result
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_reduce() {
assert_eq!(
15,
reduce(
&vec![1, 2, 3, 4, 5],
|x: &i32, y: &i32, _: usize| { x + y },
0
)
);
assert_eq!(
120,
reduce(
&vec![1, 2, 3, 4, 5],
|x: &i32, y: &i32, _: usize| { x * y },
1
)
);
}
}