Skip to content

Commit b72d3d3

Browse files
committed
Added fold method to solution of iterators5
1 parent cb60c88 commit b72d3d3

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

solutions/18_iterators/iterators5.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,17 @@ fn count_collection_iterator_flat(
6464
.count()
6565
}
6666

67+
// Equivalent to `count_collection_iterator`, `count_collection_iterator_flat` and `count_iterator`
68+
// iterating over the collection with an accumulator in order to avoid the sum step after.
69+
fn count_collection_iterator_fold(
70+
collection: &[HashMap<String, Progress>],
71+
value: Progress,
72+
) -> usize {
73+
collection
74+
.iter()
75+
.fold(0, |acc, map| acc + count_iterator(map, value))
76+
}
77+
6778
fn main() {
6879
// You can optionally experiment here.
6980
}
@@ -133,20 +144,23 @@ mod tests {
133144
let collection = get_vec_map();
134145
assert_eq!(count_collection_iterator(&collection, Complete), 6);
135146
assert_eq!(count_collection_iterator_flat(&collection, Complete), 6);
147+
assert_eq!(count_collection_iterator_fold(&collection, Complete), 6);
136148
}
137149

138150
#[test]
139151
fn count_collection_some() {
140152
let collection = get_vec_map();
141153
assert_eq!(count_collection_iterator(&collection, Some), 1);
142154
assert_eq!(count_collection_iterator_flat(&collection, Some), 1);
155+
assert_eq!(count_collection_iterator_fold(&collection, Some), 1);
143156
}
144157

145158
#[test]
146159
fn count_collection_none() {
147160
let collection = get_vec_map();
148161
assert_eq!(count_collection_iterator(&collection, None), 4);
149162
assert_eq!(count_collection_iterator_flat(&collection, None), 4);
163+
assert_eq!(count_collection_iterator_fold(&collection, None), 4);
150164
}
151165

152166
#[test]

0 commit comments

Comments
 (0)