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 find_or_last method to Itertools trait #535

Merged
merged 7 commits into from May 4, 2021
Merged
Changes from all 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
44 changes: 43 additions & 1 deletion src/lib.rs
Expand Up @@ -1730,7 +1730,49 @@ pub trait Itertools : Iterator {
}
None
}

/// Find the value of the first element satisfying a predicate or return the last element, if any.
///
/// The iterator is not advanced past the first element found.
///
/// ```
/// use itertools::Itertools;
///
/// let numbers = [1, 2, 3, 4];
/// assert_eq!(numbers.iter().find_or_last(|&&x| x > 5), Some(&4));
/// assert_eq!(numbers.iter().find_or_last(|&&x| x > 2), Some(&3));
/// assert_eq!(std::iter::empty::<i32>().find_or_last(|&x| x > 5), None);
/// ```
fn find_or_last<P>(mut self, mut predicate: P) -> Option<Self::Item>
where Self: Sized,
P: FnMut(&Self::Item) -> bool,
{
let mut prev = None;
self.find_map(|x| if predicate(&x) { Some(x) } else { prev = Some(x); None })
.or(prev)
}
/// Find the value of the first element satisfying a predicate or return the first element, if any.
///
/// The iterator is not advanced past the first element found.
///
/// ```
/// use itertools::Itertools;
///
/// let numbers = [1, 2, 3, 4];
/// assert_eq!(numbers.iter().find_or_first(|&&x| x > 5), Some(&1));
/// assert_eq!(numbers.iter().find_or_first(|&&x| x > 2), Some(&3));
/// assert_eq!(std::iter::empty::<i32>().find_or_first(|&x| x > 5), None);
/// ```
fn find_or_first<P>(mut self, mut predicate: P) -> Option<Self::Item>
where Self: Sized,
P: FnMut(&Self::Item) -> bool,
{
let first = self.next()?;
Some(if predicate(&first) {
first
} else {
self.find(|x| predicate(&x)).unwrap_or(first)
})
}
/// Returns `true` if the given item is present in this iterator.
///
/// This method is short-circuiting. If the given item is present in this
Expand Down