Skip to content

Commit 99a0a64

Browse files
New GroupingMap::min[_by[_key]]_in
1 parent fbf63e8 commit 99a0a64

File tree

1 file changed

+39
-8
lines changed

1 file changed

+39
-8
lines changed

src/grouping_map.rs

Lines changed: 39 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -360,7 +360,7 @@ where
360360
where
361361
V: Ord,
362362
{
363-
self.min_by(|_, v1, v2| V::cmp(v1, v2))
363+
self.min_in(HashMap::new())
364364
}
365365

366366
/// Groups elements from the `GroupingMap` source by key and finds the minimum of each group
@@ -382,14 +382,11 @@ where
382382
/// assert_eq!(lookup[&2], 8);
383383
/// assert_eq!(lookup.len(), 3);
384384
/// ```
385-
pub fn min_by<F>(self, mut compare: F) -> HashMap<K, V>
385+
pub fn min_by<F>(self, compare: F) -> HashMap<K, V>
386386
where
387387
F: FnMut(&K, &V, &V) -> Ordering,
388388
{
389-
self.reduce(|acc, key, val| match compare(key, &acc, &val) {
390-
Ordering::Less | Ordering::Equal => acc,
391-
Ordering::Greater => val,
392-
})
389+
self.min_by_in(compare, HashMap::new())
393390
}
394391

395392
/// Groups elements from the `GroupingMap` source by key and finds the element of each group
@@ -411,12 +408,12 @@ where
411408
/// assert_eq!(lookup[&2], 8);
412409
/// assert_eq!(lookup.len(), 3);
413410
/// ```
414-
pub fn min_by_key<F, CK>(self, mut f: F) -> HashMap<K, V>
411+
pub fn min_by_key<F, CK>(self, f: F) -> HashMap<K, V>
415412
where
416413
F: FnMut(&K, &V) -> CK,
417414
CK: Ord,
418415
{
419-
self.min_by(|key, v1, v2| f(key, v1).cmp(&f(key, v2)))
416+
self.min_by_key_in(f, HashMap::new())
420417
}
421418

422419
/// Groups elements from the `GroupingMap` source by key and find the maximum and minimum of
@@ -698,4 +695,38 @@ where
698695
{
699696
self.max_by_in(|key, v1, v2| f(key, v1).cmp(&f(key, v2)), map)
700697
}
698+
699+
/// Apply [`min`](Self::min) with a provided map.
700+
pub fn min_in<M>(self, map: M) -> M
701+
where
702+
V: Ord,
703+
M: Map<Key = K, Value = V>,
704+
{
705+
self.min_by_in(|_, v1, v2| V::cmp(v1, v2), map)
706+
}
707+
708+
/// Apply [`min_by`](Self::min_by) with a provided map.
709+
pub fn min_by_in<F, M>(self, mut compare: F, map: M) -> M
710+
where
711+
F: FnMut(&K, &V, &V) -> Ordering,
712+
M: Map<Key = K, Value = V>,
713+
{
714+
self.reduce_in(
715+
|acc, key, val| match compare(key, &acc, &val) {
716+
Ordering::Less | Ordering::Equal => acc,
717+
Ordering::Greater => val,
718+
},
719+
map,
720+
)
721+
}
722+
723+
/// Apply [`min_by_key`](Self::min_by_key) with a provided map.
724+
pub fn min_by_key_in<F, CK, M>(self, mut f: F, map: M) -> M
725+
where
726+
F: FnMut(&K, &V) -> CK,
727+
CK: Ord,
728+
M: Map<Key = K, Value = V>,
729+
{
730+
self.min_by_in(|key, v1, v2| f(key, v1).cmp(&f(key, v2)), map)
731+
}
701732
}

0 commit comments

Comments
 (0)