Skip to content

Commit 4d9c346

Browse files
authored
Merge pull request #2019 from Nahor/iterator5
Add alternative solution for iterators5
2 parents 652f0c7 + deed9d3 commit 4d9c346

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

solutions/18_iterators/iterators5.rs

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,23 @@ fn count_collection_iterator(collection: &[HashMap<String, Progress>], value: Pr
4747
.sum()
4848
}
4949

50+
// Equivalent to `count_collection_iterator`+`count_iterator`, iterating as if
51+
// the collection was a single container instead of a container of containers
52+
// (and more accurately, a single iterator instead of an iterator of iterators).
53+
fn count_collection_iterator_flat(
54+
collection: &[HashMap<String, Progress>],
55+
value: Progress,
56+
) -> usize {
57+
// `collection` is a slice of hash maps.
58+
// collection = [{ "variables1": Complete, "from_str": None, … },
59+
// { "variables2": Complete, … }, … ]
60+
collection
61+
.iter()
62+
.flat_map(HashMap::values) // or just `.flatten()` when wanting the default iterator (`HashMap::iter`)
63+
.filter(|val| **val == value)
64+
.count()
65+
}
66+
5067
fn main() {
5168
// You can optionally experiment here.
5269
}
@@ -121,18 +138,30 @@ mod tests {
121138
count_collection_iterator(&collection, Progress::Complete),
122139
6,
123140
);
141+
assert_eq!(
142+
count_collection_iterator_flat(&collection, Progress::Complete),
143+
6,
144+
);
124145
}
125146

126147
#[test]
127148
fn count_collection_some() {
128149
let collection = get_vec_map();
129150
assert_eq!(count_collection_iterator(&collection, Progress::Some), 1);
151+
assert_eq!(
152+
count_collection_iterator_flat(&collection, Progress::Some),
153+
1
154+
);
130155
}
131156

132157
#[test]
133158
fn count_collection_none() {
134159
let collection = get_vec_map();
135160
assert_eq!(count_collection_iterator(&collection, Progress::None), 4);
161+
assert_eq!(
162+
count_collection_iterator_flat(&collection, Progress::None),
163+
4
164+
);
136165
}
137166

138167
#[test]
@@ -145,6 +174,10 @@ mod tests {
145174
count_collection_for(&collection, progress_state),
146175
count_collection_iterator(&collection, progress_state),
147176
);
177+
assert_eq!(
178+
count_collection_for(&collection, progress_state),
179+
count_collection_iterator_flat(&collection, progress_state),
180+
);
148181
}
149182
}
150183
}

0 commit comments

Comments
 (0)