Skip to content

Commit

Permalink
Change into_group_map_by to return an HashMap and use the into_group_…
Browse files Browse the repository at this point in the history
…map.
  • Loading branch information
Sagebati committed Feb 10, 2020
1 parent b640523 commit a0f329a
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 17 deletions.
15 changes: 5 additions & 10 deletions src/group_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
use std::collections::HashMap;
use std::hash::Hash;
use std::iter::Iterator;
use HashMapIntoIter;

/// Return a `HashMap` of keys mapped to a list of their corresponding values.
///
Expand All @@ -23,18 +22,14 @@ pub fn into_group_map<I, K, V>(iter: I) -> HashMap<K, Vec<V>>
lookup
}

pub fn into_group_map_by<I, K, V>(iter: I, f: impl Fn(&V) -> K) ->HashMapIntoIter<K,Vec<V>>
pub fn into_group_map_by<I, K, V>(iter: I, f: impl Fn(&V) -> K) -> HashMap<K, Vec<V>>
where
I: Iterator<Item=V>,
K: Hash + Eq,
{
let mut lookup = HashMap::new();

for val in iter {
let key = f(&val);
lookup.entry(key).or_insert(Vec::new()).push(val);
}

lookup.into_iter()
into_group_map(
iter.map(|v| (f(&v), v))
)
}


11 changes: 4 additions & 7 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,6 @@ use std::fmt::Write;
#[cfg(feature = "use_std")]
type VecIntoIter<T> = ::std::vec::IntoIter<T>;

#[cfg(feature = "use_std")]
type HashMapIntoIter<K, V> = ::std::collections::hash_map::IntoIter<K, V>;

use std::iter::FromIterator;

#[macro_use]
Expand Down Expand Up @@ -2196,9 +2193,8 @@ pub trait Itertools: Iterator {
/// use std::collections::HashMap;
///
/// let data = vec![(0, 10), (2, 12), (3, 13), (0, 20), (3, 33), (2, 42)];
/// let lookup: HashMap<u32,Vec<(u32, u32)>> = data.clone().into_iter().into_group_map_by(|a|
/// a.0)
/// .collect();
/// let lookup: HashMap<u32,Vec<(u32, u32)>> =
/// data.clone().into_iter().into_group_map_by(|a| a.0);
///
/// assert_eq!(lookup[&0], vec![(0,10),(0,20)]);
/// assert_eq!(lookup.get(&1), None);
Expand All @@ -2208,11 +2204,12 @@ pub trait Itertools: Iterator {
/// assert_eq!(
/// data.into_iter()
/// .into_group_map_by(|x| x.0)
/// .into_iter()
/// .map(|(key, values)| (key, values.into_iter().fold(0,|acc, (_,v)| acc + v )))
/// .collect::<HashMap<u32,u32>>()[&0], 30)
/// ```
#[cfg(feature = "use_std")]
fn into_group_map_by<K, V, F>(self, f: F) -> HashMapIntoIter<K, Vec<V>>
fn into_group_map_by<K, V, F>(self, f: F) -> HashMap<K, Vec<V>>
where
Self: Iterator<Item=V> + Sized,
K: Hash + Eq,
Expand Down

0 comments on commit a0f329a

Please sign in to comment.