Skip to content

Commit

Permalink
Merge #468
Browse files Browse the repository at this point in the history
468: Create counts method and tests for it r=jswrenn a=JarredAllen

Creates the function described in #467 (I went with the name `counts`).

It currently uses `for_each` and makes a `HashMap` manually because the PR for the `into_grouping_map` function is still being worked on, but this function could easily be changed to call it once that PR is merged, if desired.

Co-authored-by: JarredAllen <jarredallen73@gmail.com>
  • Loading branch information
bors[bot] and JarredAllen committed Aug 20, 2020
2 parents 3a28cb6 + 1d05c2b commit 89f3a0d
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
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
21 changes: 21 additions & 0 deletions tests/quick.rs
Expand Up @@ -1188,3 +1188,24 @@ quickcheck! {
}
}
}

quickcheck! {
#[test]
fn counts(nums: Vec<isize>) -> TestResult {
let counts = nums.iter().counts();
for (&item, &count) in counts.iter() {
if count <= 0 {
return TestResult::failed();
}
if count != nums.iter().filter(|&x| x == item).count() {
return TestResult::failed();
}
}
for item in nums.iter() {
if !counts.contains_key(item) {
return TestResult::failed();
}
}
TestResult::passed()
}
}

0 comments on commit 89f3a0d

Please sign in to comment.