1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
//! This library provides users the possibility of grouping your iterators of various ways.
//! It is similar to Java `Collectors.groupingBy`
//!
//! It is implemented for any type which implements `Iterator`, but you can implement it to your custom iterator.
//!
//! ## Example:
//! ```rust
//! use std::collections::HashMap;
//! use crate::grouping_by::GroupingBy;
//!
//! #[derive(Debug, PartialEq)]
//! struct Point {
//!    x: i32,
//!    y: i32,
//! }
//! let array: [Point; 4] = [
//!        Point { x: 1, y: 2 },
//!        Point { x: 1, y: 3 },
//!        Point { x: 2, y: 2 },
//!        Point { x: 2, y: 2 },
//! ];
//!
//! assert_eq!(
//!     [
//!         (1, vec![&Point { x: 1, y: 2 }, &Point { x: 1, y: 3 }]),
//!         (2, vec![&Point { x: 2, y: 2 }, &Point { x: 2, y: 2 }])
//!     ]
//!     .iter()
//!     .cloned()
//!     .collect::<HashMap<i32, Vec<&Point>>>(),
//!     array.iter().grouping_by(|point| point.x)
//! );
//! ```
// TODO
// Implement two argument grouping by, just like groupingBy of Java does

use std::collections::{
    hash_map::{Entry, HashMap},
    HashSet,
};
use std::hash::Hash;

pub trait GroupingBy {
    /// The type of the Item of the iterator
    type GItem;

    /// Group by the key function given as parameter.
    /// The keys are the different values that the function can return,
    /// and the values are a `Vec` with the items of the iterator which has the key as property
    ///
    /// ## Example
    /// ```rust
    /// # use crate::grouping_by::GroupingBy;
    /// # use std::collections::{HashSet, HashMap};
    ///
    /// let numbers_grouped = [-1i8, -2, 1, 2]
    ///     .iter()
    ///     .grouping_by_as_set(|number| number.abs());
    ///
    /// assert_eq!(
    ///     numbers_grouped,
    ///     [(1, [1, -1].iter().collect()), (2, [2, -2].iter().collect())]
    ///         .iter()
    ///         .cloned()
    ///         .collect::<HashMap<i8, HashSet<&i8>>>()
    /// );
    /// ```
    fn grouping_by<K, F>(self, key: F) -> HashMap<K, Vec<Self::GItem>>
    where
        F: Fn(&Self::GItem) -> K,
        K: Eq + Hash;

    /// Group by the key function given as parameter.
    /// The keys are the different values that the function can return,
    /// and the values are a `HashSet` with the items of the iterator which has the key as property
    ///
    /// ## Example
    /// ```rust
    /// # use crate::grouping_by::GroupingBy;
    /// # use std::collections::{HashSet, HashMap};
    ///
    /// let numbers_grouped = [-1i8, -2, 1, 2]
    ///     .iter()
    ///     .grouping_by_as_set(|number| number.abs());
    ///
    /// assert_eq!(
    ///     numbers_grouped,
    ///     [(1, [1, -1].iter().collect()), (2, [2, -2].iter().collect())]
    ///         .iter()
    ///         .cloned()
    ///         .collect::<HashMap<i8, HashSet<&i8>>>()
    /// );
    /// ```
    fn grouping_by_as_set<K, F>(self, key: F) -> HashMap<K, HashSet<Self::GItem>>
    where
        Self::GItem: Eq + Hash,
        F: Fn(&Self::GItem) -> K,
        K: Eq + Hash;

    /// Count the elements of the iterator given a function
    ///
    /// ## Example
    /// ```rust
    /// # use crate::grouping_by::GroupingBy;
    /// # use std::collections::{HashSet, HashMap};
    /// let numbers_counted = [1, 2, 2, 3, 4].iter().counter(|&&x| x);
    ///
    /// assert_eq!(
    ///    numbers_counted,
    ///    [(1, 1), (2, 2), (3, 1), (4, 1)]
    ///        .iter()
    ///        .cloned()
    ///        .collect::<HashMap<i8, usize>>()
    /// )
    /// ```
    fn counter<K, F>(self, key: F) -> HashMap<K, usize>
    where
        K: Eq + Hash,
        F: Fn(&Self::GItem) -> K;

    /// Given a functions F, C and G, compute the minimum of the elements given a comparator and a finisher.
    /// Params:
    ///
    /// `key: F` -> function to create the keys of the resulting map
    ///
    /// `comparator: C` -> function to get the min value
    ///
    /// `finisher: G` -> function to perform the last transformation to the value
    fn grouping_by_min<K, F, G, O, C>(self, key: F, comparator: C, finisher: G) -> HashMap<K, O>
    where
        K: Eq + Hash,
        F: Fn(&Self::GItem) -> K,
        G: Fn(&Self::GItem) -> O,
        C: Fn(&O, &O) -> std::cmp::Ordering;

    /// Given a functions F, C and G, compute the maximum of the elements given a comparator and a finisher.
    /// Params:
    ///
    /// `key` -> function to create the keys of the resulting map
    ///
    /// `comparator` -> function to get the max value
    ///
    /// `finisher` -> function to perform the last transformation to the value
    fn grouping_by_max<K, F, G, O, C>(self, key: F, comparator: C, finisher: G) -> HashMap<K, O>
    where
        K: Eq + Hash,
        F: Fn(&Self::GItem) -> K,
        G: Fn(&Self::GItem) -> O,
        C: Fn(&O, &O) -> std::cmp::Ordering;
}

impl<T: Iterator> GroupingBy for T {
    type GItem = <T as Iterator>::Item;
    fn grouping_by<K, F>(self, key: F) -> HashMap<K, Vec<Self::GItem>>
    where
        F: Fn(&Self::GItem) -> K,
        K: Eq + Hash,
    {
        let mut map = HashMap::new();
        for item in self {
            map.entry(key(&item)).or_insert_with(Vec::new).push(item);
        }
        map
    }
    fn grouping_by_as_set<K, F>(self, key: F) -> HashMap<K, HashSet<Self::GItem>>
    where
        Self::GItem: Eq + Hash,
        F: Fn(&Self::GItem) -> K,
        K: Eq + Hash,
    {
        let mut map = HashMap::new();
        for item in self {
            map.entry(key(&item))
                .or_insert_with(HashSet::new)
                .insert(item);
        }
        map
    }
    fn counter<K, F>(self, key: F) -> HashMap<K, usize>
    where
        K: Eq + Hash,
        F: Fn(&Self::GItem) -> K,
    {
        let mut map = HashMap::new();
        for item in self {
            *map.entry(key(&item)).or_insert(0) += 1;
        }
        map
    }

    fn grouping_by_min<K, F, G, O, C>(self, key: F, comparator: C, finisher: G) -> HashMap<K, O>
    where
        K: Eq + Hash,
        F: Fn(&Self::GItem) -> K,
        G: Fn(&Self::GItem) -> O,
        C: Fn(&O, &O) -> std::cmp::Ordering,
    {
        let mut map: HashMap<K, O> = HashMap::new();
        for item in self {
            let new_value = finisher(&item);
            match map.entry(key(&item)) {
                Entry::Occupied(mut entry) => {
                    if comparator(&new_value, entry.get()) == std::cmp::Ordering::Less {
                        entry.insert(new_value);
                    }
                }
                Entry::Vacant(entry) => {
                    entry.insert(new_value);
                }
            }
        }
        map
    }

    fn grouping_by_max<K, F, G, O, C>(self, key: F, comparator: C, finisher: G) -> HashMap<K, O>
    where
        K: Eq + Hash,
        F: Fn(&Self::GItem) -> K,
        G: Fn(&Self::GItem) -> O,
        C: Fn(&O, &O) -> std::cmp::Ordering,
    {
        let mut map: HashMap<K, O> = HashMap::new();
        for item in self {
            let new_value = finisher(&item);
            match map.entry(key(&item)) {
                std::collections::hash_map::Entry::Occupied(mut entry) => {
                    if comparator(&new_value, entry.get()) == std::cmp::Ordering::Greater {
                        entry.insert(new_value);
                    }
                }
                std::collections::hash_map::Entry::Vacant(entry) => {
                    entry.insert(new_value);
                }
            }
        }
        map
    }
}