Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1530,6 +1530,25 @@ pub trait Itertools : Iterator {
{
minmax::minmax_impl(self, f, |_, _, xk, yk| xk < yk, |_, _, xk, yk| xk > yk)
}

/// Return the minimum and maximum element of an iterator, as determined by
/// the specified comparison function.
///
/// The return value is a variant of `MinMaxResult` like for `minmax()`.
///
/// For the minimum, the first minimal element is returned. For the maximum,
/// the last maximal element wins. This matches the behavior of the standard
/// `Iterator::min()` and `Iterator::max()` methods.
fn minmax_by<F>(self, compare: F) -> MinMaxResult<Self::Item>
where Self: Sized, F: Fn(&Self::Item, &Self::Item) -> Ordering
{
minmax::minmax_impl(
self,
|_| (),
|x, y, _, _| Ordering::Less == compare(x, y),
|x, y, _, _| Ordering::Greater == compare(x, y)
)
}
}

impl<T: ?Sized> Itertools for T where T: Iterator { }
Expand Down
4 changes: 4 additions & 0 deletions tests/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -976,6 +976,10 @@ fn minmax() {
let (min, max) = data.iter().minmax_by_key(|v| v.1).into_option().unwrap();
assert_eq!(min, &Val(2, 0));
assert_eq!(max, &Val(0, 2));

let (min, max) = data.iter().minmax_by(|x, y| x.1.cmp(&y.1)).into_option().unwrap();
assert_eq!(min, &Val(2, 0));
assert_eq!(max, &Val(0, 2));
}

#[test]
Expand Down