diff options
| author | Nahor <nahor.j+github@gmail.com> | 2024-07-04 15:34:37 -0700 |
|---|---|---|
| committer | Nahor <nahor.j+github@gmail.com> | 2024-07-04 16:35:39 -0700 |
| commit | deed9d3943f837f76fcf2ef30348329f1a706f2a (patch) | |
| tree | 979028e5830086cc1f1c9a08c6a1066384e0fe5f /solutions/18_iterators | |
| parent | 652f0c7676f928ed8a349ce0dc7a309f2e0b7d7a (diff) | |
Add alternative solution for iterators5
Diffstat (limited to 'solutions/18_iterators')
| -rw-r--r-- | solutions/18_iterators/iterators5.rs | 33 |
1 files changed, 33 insertions, 0 deletions
diff --git a/solutions/18_iterators/iterators5.rs b/solutions/18_iterators/iterators5.rs index 402c81b..85d9a4f 100644 --- a/solutions/18_iterators/iterators5.rs +++ b/solutions/18_iterators/iterators5.rs @@ -47,6 +47,23 @@ fn count_collection_iterator(collection: &[HashMap<String, Progress>], value: Pr .sum() } +// Equivalent to `count_collection_iterator`+`count_iterator`, iterating as if +// the collection was a single container instead of a container of containers +// (and more accurately, a single iterator instead of an iterator of iterators). +fn count_collection_iterator_flat( + collection: &[HashMap<String, Progress>], + value: Progress, +) -> usize { + // `collection` is a slice of hash maps. + // collection = [{ "variables1": Complete, "from_str": None, … }, + // { "variables2": Complete, … }, … ] + collection + .iter() + .flat_map(HashMap::values) // or just `.flatten()` when wanting the default iterator (`HashMap::iter`) + .filter(|val| **val == value) + .count() +} + fn main() { // You can optionally experiment here. } @@ -121,18 +138,30 @@ mod tests { count_collection_iterator(&collection, Progress::Complete), 6, ); + assert_eq!( + count_collection_iterator_flat(&collection, Progress::Complete), + 6, + ); } #[test] fn count_collection_some() { let collection = get_vec_map(); assert_eq!(count_collection_iterator(&collection, Progress::Some), 1); + assert_eq!( + count_collection_iterator_flat(&collection, Progress::Some), + 1 + ); } #[test] fn count_collection_none() { let collection = get_vec_map(); assert_eq!(count_collection_iterator(&collection, Progress::None), 4); + assert_eq!( + count_collection_iterator_flat(&collection, Progress::None), + 4 + ); } #[test] @@ -145,6 +174,10 @@ mod tests { count_collection_for(&collection, progress_state), count_collection_iterator(&collection, progress_state), ); + assert_eq!( + count_collection_for(&collection, progress_state), + count_collection_iterator_flat(&collection, progress_state), + ); } } } |
