Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Itertools.counts_by. #515

Merged
merged 6 commits into from Jan 16, 2021
Merged
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
41 changes: 41 additions & 0 deletions src/lib.rs
Expand Up @@ -3048,6 +3048,47 @@ pub trait Itertools : Iterator {
self.for_each(|item| *counts.entry(item).or_default() += 1);
counts
}

/// Collect the items in this iterator and return a `HashMap` which
/// contains each item that appears in the iterator and the number
/// of times it appears,
/// determining identity using a keying function.
///
/// ```
/// struct Character {
mmirate marked this conversation as resolved.
Show resolved Hide resolved
/// first_name: &'static str,
/// last_name: &'static str,
/// }
///
/// let characters =
/// vec![
/// Character { first_name: "Amy", last_name: "Pond" },
/// Character { first_name: "Amy", last_name: "Wong" },
/// Character { first_name: "Amy", last_name: "Santiago" },
/// Character { first_name: "James", last_name: "Bond" },
/// Character { first_name: "James", last_name: "Sullivan" },
/// Character { first_name: "James", last_name: "Norington" },
/// Character { first_name: "James", last_name: "Kirk" },
/// ];
///
/// let first_name_frequency =
/// characters
/// .into_iter()
/// .counts_by(|c| c.first_name);
///
/// assert_eq!(first_name_frequency["Amy"], 3);
/// assert_eq!(first_name_frequency["James"], 4);
/// assert_eq!(first_name_frequency.contains_key("Asha"), false);
/// ```
#[cfg(feature = "use_std")]
fn counts_by<K, F>(self, f: F) -> HashMap<K, usize>
where
Self: Sized,
K: Eq + Hash,
F: FnMut(Self::Item) -> K,
{
self.map(f).counts()
}
}

impl<T: ?Sized> Itertools for T where T: Iterator { }
Expand Down