Skip to content

Commit 97028c3

Browse files
authored
Merge pull request #138 from phimuemue/master
Implemented minmax_by
2 parents 73ded4e + c3ddadd commit 97028c3

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

src/lib.rs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1530,6 +1530,25 @@ pub trait Itertools : Iterator {
15301530
{
15311531
minmax::minmax_impl(self, f, |_, _, xk, yk| xk < yk, |_, _, xk, yk| xk > yk)
15321532
}
1533+
1534+
/// Return the minimum and maximum element of an iterator, as determined by
1535+
/// the specified comparison function.
1536+
///
1537+
/// The return value is a variant of `MinMaxResult` like for `minmax()`.
1538+
///
1539+
/// For the minimum, the first minimal element is returned. For the maximum,
1540+
/// the last maximal element wins. This matches the behavior of the standard
1541+
/// `Iterator::min()` and `Iterator::max()` methods.
1542+
fn minmax_by<F>(self, compare: F) -> MinMaxResult<Self::Item>
1543+
where Self: Sized, F: Fn(&Self::Item, &Self::Item) -> Ordering
1544+
{
1545+
minmax::minmax_impl(
1546+
self,
1547+
|_| (),
1548+
|x, y, _, _| Ordering::Less == compare(x, y),
1549+
|x, y, _, _| Ordering::Greater == compare(x, y)
1550+
)
1551+
}
15331552
}
15341553

15351554
impl<T: ?Sized> Itertools for T where T: Iterator { }

tests/tests.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -976,6 +976,10 @@ fn minmax() {
976976
let (min, max) = data.iter().minmax_by_key(|v| v.1).into_option().unwrap();
977977
assert_eq!(min, &Val(2, 0));
978978
assert_eq!(max, &Val(0, 2));
979+
980+
let (min, max) = data.iter().minmax_by(|x, y| x.1.cmp(&y.1)).into_option().unwrap();
981+
assert_eq!(min, &Val(2, 0));
982+
assert_eq!(max, &Val(0, 2));
979983
}
980984

981985
#[test]

0 commit comments

Comments
 (0)