-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathfind_last.rs
39 lines (33 loc) · 1 KB
/
find_last.rs
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
//! This method is like `find` except that it iterates over elements of
//! `collection` from right to left.
//!
//! Example
//! ```
//! use lodash_rust::find_last;
//!
//! let res = find_last::new([1, 2, 3, 4].to_vec(), &|x: i32| x % 2 == 1, 3);
//! println!("{res:?}") // Some(3)
//! ```
pub fn new<T: Copy>(array: Vec<T>, f: &dyn Fn(T) -> bool, from_index: usize) -> Option<T> {
if from_index > array.len() - 1 {
return None;
}
let mut loop_index = 1;
if from_index > 0 {
loop_index = from_index;
}
for index in 0..loop_index {
let value = array[from_index - index];
if f(value) {
return Some(value);
}
}
None
}
#[test]
fn test_new() {
assert_eq!(new([1, 2, 3, 4].to_vec(), &|x: i32| x < 3, 3), Some(2));
assert_eq!(new([1, 2, 3, 4].to_vec(), &|x: i32| x % 2 == 1, 3), Some(3));
assert_eq!(new([1, 2, 3, 4].to_vec(), &|x: i32| x < 3, 5), None);
assert_eq!(new([1, 2, 3, 4].to_vec(), &|x: i32| x == 1, 0), Some(1));
}