-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathfind_key.rs
38 lines (34 loc) · 941 Bytes
/
find_key.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
//! This method is like `find` except that it returns the key of the first
//! element `predicate` returns truthy for instead of the element itself.
//!
//! Example
//! ```
//! use lodash_rust::find_key;
//! use std::collections::HashMap;
//!
//! let mut map: HashMap<char, u64> = HashMap::new();
//! map.insert('a', 1);
//! map.insert('b', 2);
//! map.insert('c', 3);
//!
//! let res = find_key::new(&map, |&x| x % 2 == 1);
//! println!("{res:?}") // Some('c')
//! ```
use std::collections::HashMap;
pub fn new<K: Copy, V, F: Fn(&V) -> bool>(h: &HashMap<K, V>, p: F) -> Option<K> {
for (k, v) in h {
if p(v) {
return Some(*k);
}
}
None
}
#[test]
fn test_new() {
let mut map: HashMap<char, u64> = HashMap::new();
map.insert('a', 1);
map.insert('b', 2);
map.insert('c', 3);
assert_eq!(new(&map, |&x| x % 3 == 1), Some('a'));
assert_eq!(new(&map, |&x| x == 2), Some('b'));
}