Created
July 23, 2024 10:10
-
-
Save volgar1x/b2bbcfbac2de030b6d5d256b34e46282 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pub trait IteratorExt: std::iter::Iterator { | |
fn group_by<F, K, G>(self, f: F) -> HashMap<K, Vec<G>> | |
where | |
Self: Sized, | |
K: Eq + Hash, | |
F: FnMut(Self::Item) -> (K, G); | |
} | |
impl<T> IteratorExt for T | |
where | |
T: std::iter::Iterator + ?Sized, | |
{ | |
fn group_by<F, K, G>(self, mut f: F) -> HashMap<K, Vec<G>> | |
where | |
Self: Sized, | |
K: Eq + Hash, | |
F: FnMut(Self::Item) -> (K, G), | |
{ | |
let mut accum = HashMap::<K, Vec<G>>::new(); | |
for item in self { | |
let (k, g) = f(item); | |
if let Some(group) = accum.get_mut(&k) { | |
group.push(g); | |
} else { | |
accum.insert(k, vec![g]); | |
} | |
} | |
accum | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment