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
/// Iterates over elements of collection, returning the last one and its index that pass predicate function.
///
/// * predicate function signature: ```fn(item: &T, index: usize) -> bool```
///
/// # Arguments
///
/// * `collection` - The collection to iterate over.
///
/// * `predicate` - The check function invoked per iteration.
///
/// * `find_from` - The position to start find.
///
///
/// # Returns
///
/// Returns the last element and its index which pass the predicate function check.
///
/// # Examples
///
/// ```
/// use rufl::collection;
///
/// assert_eq!(Some((4, 3)), collection::find_last([1, 2, 3, 4, 5], &|n: &i32, _i: usize| *n > 3, 3));
///
/// assert_eq!(None, collection::find_last([1, 2, 3, 4, 5], &|n: &i32, _i: usize| *n > 3, 5));
/// ```
pub fn find_last<C: AsRef<[T]>, T: Clone>(
collection: C,
predicate: impl Fn(&T, usize) -> bool,
find_from: usize,
) -> Option<(T, usize)> {
let vec = collection.as_ref();
if find_from > vec.len() - 1 {
return None;
}
let mut find_end = 1;
if find_from > 0 {
find_end = find_from;
}
for i in 0..find_end {
let item = &vec[find_from - i];
if predicate(item, find_from - i) {
return Some((item.clone(), find_from - i));
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_find_last() {
assert_eq!(
Some((4, 3)),
find_last([1, 2, 3, 4, 5], &|n: &i32, _i: usize| *n > 3, 3)
);
assert_eq!(
Some((5, 4)),
find_last([1, 2, 3, 4, 5], &|n: &i32, _i: usize| *n > 3, 4)
);
assert_eq!(
None,
find_last([1, 2, 3, 4, 5], &|n: &i32, _i: usize| *n > 3, 5)
);
assert_eq!(
Some((5, 4)),
find_last([1, 2, 3, 4, 5], &|n: &i32, _i: usize| *n % 2 != 0, 4)
);
}
}