|
2 | 2 |
|
3 | 3 | use crate::{
|
4 | 4 | adaptors::map::{MapSpecialCase, MapSpecialCaseFn},
|
| 5 | + generic_containers::Map, |
5 | 6 | MinMaxResult,
|
6 | 7 | };
|
7 | 8 | use std::cmp::Ordering;
|
@@ -109,20 +110,11 @@ where
|
109 | 110 | /// assert_eq!(lookup[&3], 7);
|
110 | 111 | /// assert_eq!(lookup.len(), 3); // The final keys are only 0, 1 and 2
|
111 | 112 | /// ```
|
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> |
113 | 114 | where
|
114 | 115 | FO: FnMut(Option<R>, &K, V) -> Option<R>,
|
115 | 116 | {
|
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()) |
126 | 118 | }
|
127 | 119 |
|
128 | 120 | /// Groups elements from the `GroupingMap` source by key and applies `operation` to the elements
|
@@ -605,3 +597,27 @@ where
|
605 | 597 | self.fold_first(|acc, _, val| acc * val)
|
606 | 598 | }
|
607 | 599 | }
|
| 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