diff --git a/src/lib.rs b/src/lib.rs index dfcee9e63..8789a39ce 100755 --- a/src/lib.rs +++ b/src/lib.rs @@ -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(self, compare: F) -> MinMaxResult + 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 Itertools for T where T: Iterator { } diff --git a/tests/tests.rs b/tests/tests.rs index 4701703d2..3245ae78b 100644 --- a/tests/tests.rs +++ b/tests/tests.rs @@ -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]