Skip to content

Commit 4a52f3c

Browse files
committed
Implement alternative implementation of find_or_last
using accumulator variable and find_map
1 parent f02cfd9 commit 4a52f3c

File tree

1 file changed

+4
-9
lines changed

1 file changed

+4
-9
lines changed

src/lib.rs

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1742,18 +1742,13 @@ pub trait Itertools : Iterator {
17421742
/// assert_eq!(numbers.iter().find_or_last(|&&x| x > 2), Some(&3));
17431743
/// assert_eq!(std::iter::empty::<i32>().find_or_last(|&x| x > 5), None);
17441744
/// ```
1745-
fn find_or_last<P>(mut self, predicate: P) -> Option<Self::Item>
1745+
fn find_or_last<P>(mut self, mut predicate: P) -> Option<Self::Item>
17461746
where Self: Sized,
17471747
P: FnMut(&Self::Item) -> bool,
17481748
{
1749-
#[inline]
1750-
fn check<T>(mut predicate: impl FnMut(&T) -> bool) -> impl FnMut(Option<T>, T) -> Result<Option<T>, T> {
1751-
move |_, x| {
1752-
if predicate(&x) { Result::Err(x) } else { Result::Ok(Some(x)) }
1753-
}
1754-
}
1755-
1756-
self.try_fold(None, check(predicate)).unwrap_or_else(Some)
1749+
let mut prev = None;
1750+
self.find_map(|x| if predicate(&x) { Some(x) } else { prev = Some(x); None })
1751+
.or(prev)
17571752
}
17581753
/// Returns `true` if the given item is present in this iterator.
17591754
///

0 commit comments

Comments
 (0)