Skip to content

Commit 4295baa

Browse files
New GroupingMap::max[_by[_key]]_in
1 parent d4b3723 commit 4295baa

File tree

1 file changed

+42
-8
lines changed

1 file changed

+42
-8
lines changed

src/grouping_map.rs

Lines changed: 42 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -281,7 +281,7 @@ where
281281
where
282282
V: Ord,
283283
{
284-
self.max_by(|_, v1, v2| V::cmp(v1, v2))
284+
self.max_in(HashMap::new())
285285
}
286286

287287
/// Groups elements from the `GroupingMap` source by key and finds the maximum of each group
@@ -303,14 +303,11 @@ where
303303
/// assert_eq!(lookup[&2], 5);
304304
/// assert_eq!(lookup.len(), 3);
305305
/// ```
306-
pub fn max_by<F>(self, mut compare: F) -> HashMap<K, V>
306+
pub fn max_by<F>(self, compare: F) -> HashMap<K, V>
307307
where
308308
F: FnMut(&K, &V, &V) -> Ordering,
309309
{
310-
self.reduce(|acc, key, val| match compare(key, &acc, &val) {
311-
Ordering::Less | Ordering::Equal => val,
312-
Ordering::Greater => acc,
313-
})
310+
self.max_by_in(compare, HashMap::new())
314311
}
315312

316313
/// Groups elements from the `GroupingMap` source by key and finds the element of each group
@@ -332,12 +329,12 @@ where
332329
/// assert_eq!(lookup[&2], 5);
333330
/// assert_eq!(lookup.len(), 3);
334331
/// ```
335-
pub fn max_by_key<F, CK>(self, mut f: F) -> HashMap<K, V>
332+
pub fn max_by_key<F, CK>(self, f: F) -> HashMap<K, V>
336333
where
337334
F: FnMut(&K, &V) -> CK,
338335
CK: Ord,
339336
{
340-
self.max_by(|key, v1, v2| f(key, v1).cmp(&f(key, v2)))
337+
self.max_by_key_in(f, HashMap::new())
341338
}
342339

343340
/// Groups elements from the `GroupingMap` source by key and finds the minimum of each group.
@@ -674,4 +671,41 @@ where
674671

675672
map
676673
}
674+
675+
/// Apply [`max`](Self::max) with a provided empty map
676+
/// (`BTreeMap` or `HashMap` with any hasher).
677+
pub fn max_in<M>(self, map: M) -> M
678+
where
679+
V: Ord,
680+
M: Map<Key = K, Value = V>,
681+
{
682+
self.max_by_in(|_, v1, v2| V::cmp(v1, v2), map)
683+
}
684+
685+
/// Apply [`max_by`](Self::max_by) with a provided empty map
686+
/// (`BTreeMap` or `HashMap` with any hasher).
687+
pub fn max_by_in<F, M>(self, mut compare: F, map: M) -> M
688+
where
689+
F: FnMut(&K, &V, &V) -> Ordering,
690+
M: Map<Key = K, Value = V>,
691+
{
692+
self.reduce_in(
693+
|acc, key, val| match compare(key, &acc, &val) {
694+
Ordering::Less | Ordering::Equal => val,
695+
Ordering::Greater => acc,
696+
},
697+
map,
698+
)
699+
}
700+
701+
/// Apply [`max_by_key`](Self::max_by_key) with a provided empty map
702+
/// (`BTreeMap` or `HashMap` with any hasher).
703+
pub fn max_by_key_in<F, CK, M>(self, mut f: F, map: M) -> M
704+
where
705+
F: FnMut(&K, &V) -> CK,
706+
CK: Ord,
707+
M: Map<Key = K, Value = V>,
708+
{
709+
self.max_by_in(|key, v1, v2| f(key, v1).cmp(&f(key, v2)), map)
710+
}
677711
}

0 commit comments

Comments
 (0)