|
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;
|
@@ -110,20 +111,11 @@ where
|
110 | 111 | /// assert_eq!(lookup[&3], 7);
|
111 | 112 | /// assert_eq!(lookup.len(), 3); // The final keys are only 0, 1 and 2
|
112 | 113 | /// ```
|
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> |
114 | 115 | where
|
115 | 116 | FO: FnMut(Option<R>, &K, V) -> Option<R>,
|
116 | 117 | {
|
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()) |
127 | 119 | }
|
128 | 120 |
|
129 | 121 | /// Groups elements from the `GroupingMap` source by key and applies `operation` to the elements
|
@@ -615,3 +607,25 @@ where
|
615 | 607 | self.reduce(|acc, _, val| acc * val)
|
616 | 608 | }
|
617 | 609 | }
|
| 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