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

Create counts method and tests for it #468

Merged
merged 2 commits into from Aug 20, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
24 changes: 24 additions & 0 deletions src/lib.rs
Expand Up @@ -2807,6 +2807,30 @@ pub trait Itertools : Iterator {
{
multipeek_impl::multipeek(self)
}

/// 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.
///
/// # Examples
/// ```
/// # use itertools::Itertools;
/// let counts = [1, 1, 1, 3, 3, 5].into_iter().counts();
/// assert_eq!(counts[&1], 3);
/// assert_eq!(counts[&3], 2);
/// assert_eq!(counts[&5], 1);
/// assert_eq!(counts.get(&0), None);
/// ```
#[cfg(feature = "use_std")]
fn counts(self) -> HashMap<Self::Item, usize>
where
Self: Sized,
Self::Item: Eq + Hash,
{
let mut counts = HashMap::new();
self.for_each(|item| *counts.entry(item).or_default() += 1);
counts
}
}

impl<T: ?Sized> Itertools for T where T: Iterator { }
Expand Down
13 changes: 13 additions & 0 deletions tests/test_std.rs
Expand Up @@ -913,3 +913,16 @@ fn tree_fold1() {
assert_eq!(actual, expected);
}
}

#[test]
fn counts() {
let a: [usize; 0] = [];
assert_eq!(0, a.iter().counts().len());
let b = [1, 1, 1, 2, 2, 3];
let b_counts = b.iter().counts();
assert_eq!(3, b_counts.len());
assert_eq!(Some(&3), b_counts.get(&1));
assert_eq!(Some(&2), b_counts.get(&2));
assert_eq!(Some(&1), b_counts.get(&3));
assert_eq!(None, b_counts.get(&4));
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wouldn't a quicktest be better? You can probably adapt the test I wrote in my PR for my count method:

https://github.com/rust-itertools/itertools/pull/465/files#diff-934f6ed12102bba0b289ee2855cb9bd1R1306-R1324

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it would, and I've now included that. Thanks for the suggestion.