|
21 | 21 | //! # }) }
|
22 | 22 | //! ```
|
23 | 23 |
|
| 24 | +use std::cmp::Ordering; |
24 | 25 | use std::pin::Pin;
|
25 | 26 |
|
26 | 27 | use cfg_if::cfg_if;
|
27 | 28 |
|
| 29 | +use super::min_by::MinBy; |
28 | 30 | use crate::future::Future;
|
29 | 31 | use crate::task::{Context, Poll};
|
30 | 32 | use std::marker::PhantomData;
|
@@ -118,6 +120,39 @@ pub trait Stream {
|
118 | 120 | }
|
119 | 121 | }
|
120 | 122 |
|
| 123 | + /// Returns the element that gives the minimum value with respect to the |
| 124 | + /// specified comparison function. If several elements are equally minimum, |
| 125 | + /// the first element is returned. If the stream is empty, `None` is returned. |
| 126 | + /// |
| 127 | + /// # Examples |
| 128 | + /// |
| 129 | + /// ``` |
| 130 | + /// # fn main() { async_std::task::block_on(async { |
| 131 | + /// # |
| 132 | + /// use std::collections::VecDeque; |
| 133 | + /// use async_std::stream::Stream; |
| 134 | + /// |
| 135 | + /// let s: VecDeque<usize> = vec![1, 2, 3].into_iter().collect(); |
| 136 | + /// |
| 137 | + /// let min = Stream::min_by(s.clone(), |x, y| x.cmp(y)).await; |
| 138 | + /// assert_eq!(min, Some(1)); |
| 139 | + /// |
| 140 | + /// let min = Stream::min_by(s, |x, y| y.cmp(x)).await; |
| 141 | + /// assert_eq!(min, Some(3)); |
| 142 | + /// |
| 143 | + /// let min = Stream::min_by(VecDeque::<usize>::new(), |x, y| x.cmp(y)).await; |
| 144 | + /// assert_eq!(min, None); |
| 145 | + /// # |
| 146 | + /// # }) } |
| 147 | + /// ``` |
| 148 | + fn min_by<F>(self, compare: F) -> MinBy<Self, F> |
| 149 | + where |
| 150 | + Self: Sized + Unpin, |
| 151 | + F: FnMut(&Self::Item, &Self::Item) -> Ordering, |
| 152 | + { |
| 153 | + MinBy::new(self, compare) |
| 154 | + } |
| 155 | + |
121 | 156 | /// Tests if every element of the stream matches a predicate.
|
122 | 157 | ///
|
123 | 158 | /// `all()` takes a closure that returns `true` or `false`. It applies
|
|
0 commit comments