Skip to content

Commit 79ea22b

Browse files
New GroupingMap::aggregate_in
1 parent f6da436 commit 79ea22b

File tree

1 file changed

+25
-11
lines changed

1 file changed

+25
-11
lines changed

src/grouping_map.rs

Lines changed: 25 additions & 11 deletions
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;
@@ -110,20 +111,11 @@ where
110111
/// assert_eq!(lookup[&3], 7);
111112
/// assert_eq!(lookup.len(), 3); // The final keys are only 0, 1 and 2
112113
/// ```
113-
pub fn aggregate<FO, R>(self, mut operation: FO) -> HashMap<K, R>
114+
pub fn aggregate<FO, R>(self, operation: FO) -> HashMap<K, R>
114115
where
115116
FO: FnMut(Option<R>, &K, V) -> Option<R>,
116117
{
117-
let mut destination_map = HashMap::new();
118-
119-
self.iter.for_each(|(key, val)| {
120-
let acc = destination_map.remove(&key);
121-
if let Some(op_res) = operation(acc, &key, val) {
122-
destination_map.insert(key, op_res);
123-
}
124-
});
125-
126-
destination_map
118+
self.aggregate_in(operation, HashMap::new())
127119
}
128120

129121
/// Groups elements from the `GroupingMap` source by key and applies `operation` to the elements
@@ -615,3 +607,25 @@ where
615607
self.reduce(|acc, _, val| acc * val)
616608
}
617609
}
610+
611+
impl<I, K, V> GroupingMap<I>
612+
where
613+
I: Iterator<Item = (K, V)>,
614+
K: Eq,
615+
{
616+
/// Apply [`aggregate`](Self::aggregate) with a provided map.
617+
pub fn aggregate_in<FO, R, M>(self, mut operation: FO, mut map: M) -> M
618+
where
619+
FO: FnMut(Option<R>, &K, V) -> Option<R>,
620+
M: Map<Key = K, Value = R>,
621+
{
622+
self.iter.for_each(|(key, val)| {
623+
let acc = map.remove(&key);
624+
if let Some(op_res) = operation(acc, &key, val) {
625+
map.insert(key, op_res);
626+
}
627+
});
628+
629+
map
630+
}
631+
}

0 commit comments

Comments
 (0)