Skip to content

Commit df7720d

Browse files
New GroupingMap::aggregate_in
Instead of `debug_assert!(map.is_empty());` we could alternatively `map.clear();`. I have a preference for it but check it's empty is less surprising, right?! Anyway, the documentation should state one or the other.
1 parent 3049c29 commit df7720d

File tree

1 file changed

+27
-11
lines changed

1 file changed

+27
-11
lines changed

src/grouping_map.rs

+27-11
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
use crate::{
44
adaptors::map::{MapSpecialCase, MapSpecialCaseFn},
5+
generic_containers::Map,
56
MinMaxResult,
67
};
78
use std::cmp::Ordering;
@@ -109,20 +110,11 @@ where
109110
/// assert_eq!(lookup[&3], 7);
110111
/// assert_eq!(lookup.len(), 3); // The final keys are only 0, 1 and 2
111112
/// ```
112-
pub fn aggregate<FO, R>(self, mut operation: FO) -> HashMap<K, R>
113+
pub fn aggregate<FO, R>(self, operation: FO) -> HashMap<K, R>
113114
where
114115
FO: FnMut(Option<R>, &K, V) -> Option<R>,
115116
{
116-
let mut destination_map = HashMap::new();
117-
118-
self.iter.for_each(|(key, val)| {
119-
let acc = destination_map.remove(&key);
120-
if let Some(op_res) = operation(acc, &key, val) {
121-
destination_map.insert(key, op_res);
122-
}
123-
});
124-
125-
destination_map
117+
self.aggregate_in(operation, HashMap::new())
126118
}
127119

128120
/// Groups elements from the `GroupingMap` source by key and applies `operation` to the elements
@@ -605,3 +597,27 @@ where
605597
self.fold_first(|acc, _, val| acc * val)
606598
}
607599
}
600+
601+
impl<I, K, V> GroupingMap<I>
602+
where
603+
I: Iterator<Item = (K, V)>,
604+
{
605+
/// Apply [`aggregate`](Self::aggregate) with a provided empty map
606+
/// (`BTreeMap` or `HashMap` with any hasher).
607+
pub fn aggregate_in<FO, R, M>(self, mut operation: FO, mut map: M) -> M
608+
where
609+
FO: FnMut(Option<R>, &K, V) -> Option<R>,
610+
M: Map<Key = K, Value = R>,
611+
{
612+
debug_assert!(map.is_empty());
613+
614+
self.iter.for_each(|(key, val)| {
615+
let acc = map.remove(&key);
616+
if let Some(op_res) = operation(acc, &key, val) {
617+
map.insert(key, op_res);
618+
}
619+
});
620+
621+
map
622+
}
623+
}

0 commit comments

Comments
 (0)