Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
FEAT: Add {min,max}_set(_by{_key)?)? functions
The function min_set returns a Vec of all the minimum values. All variants for max and with key extraction and comparison functions are added also. Since the functions need to return an unknown number of values and the values are not known until the iterator is finished, the function needs to allocate memory. Therefore Vec is used for returning the values.
- Loading branch information
Showing
3 changed files
with
280 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
/// Implementation guts for `min_set`, `min_set_by`, and `min_set_by_key`. | ||
pub fn min_set_impl<I, K, F, L>(mut it: I, | ||
mut key_for: F, | ||
mut lt: L) -> Option<Vec<I::Item>> | ||
where I: Iterator, | ||
F: FnMut(&I::Item) -> K, | ||
L: FnMut(&I::Item, &I::Item, &K, &K) -> bool, | ||
{ | ||
let (mut result, mut current_key) = match it.next() { | ||
None => return None, | ||
Some(element) => { | ||
let key = key_for(&element); | ||
(vec![element], key) | ||
} | ||
}; | ||
|
||
for element in it { | ||
let key = key_for(&element); | ||
if lt(&element, &result[0], &key, ¤t_key) { | ||
result.clear(); | ||
result.push(element); | ||
current_key = key; | ||
} else if !lt(&result[0], &element, ¤t_key, &key) { | ||
result.push(element); | ||
} | ||
} | ||
|
||
Some(result) | ||
} | ||
|
||
/// Implementation guts for `ax_set`, `max_set_by`, and `max_set_by_key`. | ||
pub fn max_set_impl<I, K, F, L>(it: I, | ||
key_for: F, | ||
mut lt: L) -> Option<Vec<I::Item>> | ||
where I: Iterator, | ||
F: FnMut(&I::Item) -> K, | ||
L: FnMut(&I::Item, &I::Item, &K, &K) -> bool, | ||
{ | ||
min_set_impl(it, key_for, |it1, it2, key1, key2| lt(it2, it1, key2, key1)) | ||
} | ||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters