@@ -47,6 +47,23 @@ fn count_collection_iterator(collection: &[HashMap<String, Progress>], value: Pr
47
47
. sum ( )
48
48
}
49
49
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
+
50
67
fn main ( ) {
51
68
// You can optionally experiment here.
52
69
}
@@ -121,18 +138,30 @@ mod tests {
121
138
count_collection_iterator( & collection, Progress :: Complete ) ,
122
139
6 ,
123
140
) ;
141
+ assert_eq ! (
142
+ count_collection_iterator_flat( & collection, Progress :: Complete ) ,
143
+ 6 ,
144
+ ) ;
124
145
}
125
146
126
147
#[ test]
127
148
fn count_collection_some ( ) {
128
149
let collection = get_vec_map ( ) ;
129
150
assert_eq ! ( count_collection_iterator( & collection, Progress :: Some ) , 1 ) ;
151
+ assert_eq ! (
152
+ count_collection_iterator_flat( & collection, Progress :: Some ) ,
153
+ 1
154
+ ) ;
130
155
}
131
156
132
157
#[ test]
133
158
fn count_collection_none ( ) {
134
159
let collection = get_vec_map ( ) ;
135
160
assert_eq ! ( count_collection_iterator( & collection, Progress :: None ) , 4 ) ;
161
+ assert_eq ! (
162
+ count_collection_iterator_flat( & collection, Progress :: None ) ,
163
+ 4
164
+ ) ;
136
165
}
137
166
138
167
#[ test]
@@ -145,6 +174,10 @@ mod tests {
145
174
count_collection_for( & collection, progress_state) ,
146
175
count_collection_iterator( & collection, progress_state) ,
147
176
) ;
177
+ assert_eq ! (
178
+ count_collection_for( & collection, progress_state) ,
179
+ count_collection_iterator_flat( & collection, progress_state) ,
180
+ ) ;
148
181
}
149
182
}
150
183
}
0 commit comments