Skip to content

Commit

Permalink
Create counts method and tests for it
Browse files Browse the repository at this point in the history
  • Loading branch information
JarredAllen committed Aug 12, 2020
1 parent 3a28cb6 commit cc88a2d
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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));
}

0 comments on commit cc88a2d

Please sign in to comment.