Skip to content

Commit 742a678

Browse files
New GroupingMap::reduce_in
1 parent cb72ea1 commit 742a678

File tree

1 file changed

+19
-7
lines changed

1 file changed

+19
-7
lines changed

src/grouping_map.rs

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -219,16 +219,11 @@ where
219219
/// assert_eq!(lookup[&2], 2 + 5);
220220
/// assert_eq!(lookup.len(), 3);
221221
/// ```
222-
pub fn reduce<FO>(self, mut operation: FO) -> HashMap<K, V>
222+
pub fn reduce<FO>(self, operation: FO) -> HashMap<K, V>
223223
where
224224
FO: FnMut(V, &K, V) -> V,
225225
{
226-
self.aggregate(|acc, key, val| {
227-
Some(match acc {
228-
Some(acc) => operation(acc, key, val),
229-
None => val,
230-
})
231-
})
226+
self.reduce_in(operation, HashMap::new())
232227
}
233228

234229
/// See [`.reduce()`](GroupingMap::reduce).
@@ -651,4 +646,21 @@ where
651646
{
652647
self.fold_with_in(|_, _| init.clone(), operation, map)
653648
}
649+
650+
/// Apply [`reduce`](Self::reduce) with a provided map.
651+
pub fn reduce_in<FO, M>(self, mut operation: FO, map: M) -> M
652+
where
653+
FO: FnMut(V, &K, V) -> V,
654+
M: Map<Key = K, Value = V>,
655+
{
656+
self.aggregate_in(
657+
|acc, key, val| {
658+
Some(match acc {
659+
Some(acc) => operation(acc, key, val),
660+
None => val,
661+
})
662+
},
663+
map,
664+
)
665+
}
654666
}

0 commit comments

Comments
 (0)