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.contains #514

Merged
merged 9 commits into from
Jan 13, 2021
Merged
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
47 changes: 47 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1608,6 +1608,53 @@ pub trait Itertools : Iterator {
None
}

/// Check whether the iterator contains an item.
///
/// If the iterator contains the item prior to its end,
/// this method will short-circuit and only partially
/// exhaust the iterator.
mmirate marked this conversation as resolved.
Show resolved Hide resolved
///
/// ```
/// use itertools::Itertools;
///
/// let data = vec![
/// "foo".to_owned(),
/// "bar".to_owned(),
/// "baz".to_owned(),
/// ];
/// // this could get expensive:
/// assert!(data.contains(&"foo".to_owned()));
/// // this, less so:
/// assert!(data.iter().contains("foo"));
jswrenn marked this conversation as resolved.
Show resolved Hide resolved
///
/// // now the not-as-motivating tests involving Copy data:
///
/// let data = vec![4usize, 5, 1, 3, 0, 2];
/// assert!(data.iter().contains(&4));
/// assert!(!data.iter().contains(&6));
/// for x in (0..50) {
/// assert_eq!(data.contains(&x), data.iter().contains(&x));
/// }
///
/// let mut it = data.iter();
/// assert!(!it.contains(&6));
/// assert_eq!(it.next(), None);
///
/// let mut it = data.iter();
/// assert!(it.contains(&3));
/// assert_eq!(it.next(), Some(&0));
///
/// let data : Option<usize> = None;
/// assert!(!data.into_iter().contains(0));
/// ```
mmirate marked this conversation as resolved.
Show resolved Hide resolved
fn contains<Q>(&mut self, query: Q) -> bool
where
Self: Sized,
Self::Item: PartialEq<Q>,
{
self.any(|x| x == query)
}
jswrenn marked this conversation as resolved.
Show resolved Hide resolved

/// Check whether all elements compare equal.
///
/// Empty iterators are considered to have equal elements:
Expand Down