Skip to content

Commit

Permalink
Implement min_by
Browse files Browse the repository at this point in the history
  • Loading branch information
sfackler committed Mar 10, 2019
1 parent 60acd0a commit 04620cd
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
23 changes: 22 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -636,7 +636,7 @@ pub trait FallibleIterator {
}

/// Returns the element of the iterator which gives the minimum value from
/// the function. The function may fail; such failures are returned to the caller.
/// the function.
#[inline]
fn min_by_key<B, F>(mut self, mut f: F) -> Result<Option<Self::Item>, Self::Error>
where
Expand All @@ -659,6 +659,27 @@ pub trait FallibleIterator {
Ok(Some(min.1))
}

/// Returns the element that gives the minimum value with respect to the function.
#[inline]
fn min_by<F>(mut self, mut f: F) -> Result<Option<Self::Item>, Self::Error>
where
Self: Sized,
F: FnMut(&Self::Item, &Self::Item) -> Result<Ordering, Self::Error>,
{
let mut min= match self.next()? {
Some(v) => v,
None => return Ok(None),
};

while let Some(v) = self.next()? {
if f(&min, &v)? != Ordering::Less {
min = v;
}
}

Ok(Some(min))
}

/// Returns an iterator that yields this iterator's items in the opposite
/// order.
#[inline]
Expand Down
6 changes: 6 additions & 0 deletions src/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,12 @@ fn min_by_key() {
);
}

#[test]
fn min_by() {
let it = convert(vec![0, 3, 1, -10].into_iter().map(Ok::<i32, ()>));
assert_eq!(it.min_by(|a, b| Ok(b.cmp(a))), Ok(Some(3)));
}

#[test]
fn nth() {
let mut it = convert(vec![0, 1, 2, 3].into_iter().map(Ok::<i32, ()>));
Expand Down

0 comments on commit 04620cd

Please sign in to comment.