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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
use std::collections::HashMap;
use std::hash::Hash;
/// Transforms a slice of items into a `HashMap` by applying a provided function to each item.
///
/// This function takes a slice of items and a transform function, then returns a new `HashMap<K, V>` where each key-value pair
/// is generated by applying the transform function to an element in the collection. If multiple elements produce the same key,
/// the last occurrence will overwrite previous ones.
///
/// **Time Complexity:**
/// O(n), where n is the number of elements in the collection.
///
/// # Arguments
///
/// * `collection` - A slice of items to be transformed into key-value pairs.
/// * `transform` - A function that takes an item from the collection and returns a key-value pair.
///
/// # Type Parameters
///
/// * `T` - The type of elements in the collection.
/// * `K` - The type of keys in the resulting `HashMap`. Must implement `Eq` and `Hash`.
/// * `V` - The type of values in the resulting `HashMap`.
/// * `F` - The type of the transform function. Must implement `Fn(&T) -> (K, V)`.
///
/// # Returns
///
/// * `HashMap<K, V>` - A `HashMap` where each key-value pair is the result of applying the transform function to an element in the collection.
///
/// # Examples
///
/// ```rust
/// use lowdash::slice_to_map;
/// use std::collections::HashMap;
///
/// let numbers = vec![1, 2, 3, 4, 5];
/// let map = slice_to_map(&numbers, |&x| (x, x * x));
/// let mut expected = HashMap::new();
/// expected.insert(1, 1);
/// expected.insert(2, 4);
/// expected.insert(3, 9);
/// expected.insert(4, 16);
/// expected.insert(5, 25);
/// assert_eq!(map, expected);
/// ```
///
/// ```rust
/// use lowdash::slice_to_map;
/// use std::collections::HashMap;
///
/// #[derive(Debug, PartialEq, Clone)]
/// struct Person {
/// name: String,
/// age: u32,
/// }
///
/// let people = vec![
/// Person { name: "Alice".to_string(), age: 25 },
/// Person { name: "Bob".to_string(), age: 30 },
/// Person { name: "Charlie".to_string(), age: 35 },
/// ];
///
/// let map = slice_to_map(&people, |person| (person.name.clone(), person.age));
/// let mut expected = HashMap::new();
/// expected.insert("Alice".to_string(), 25);
/// expected.insert("Bob".to_string(), 30);
/// expected.insert("Charlie".to_string(), 35);
/// assert_eq!(map, expected);
/// ```
///
/// ```rust
/// use lowdash::slice_to_map;
/// use std::collections::HashMap;
///
/// let strings = vec!["apple", "banana", "apricot", "blueberry"];
/// let map = slice_to_map(&strings, |s| (s.chars().next().unwrap(), s.len()));
/// let mut expected = HashMap::new();
/// expected.insert('a', 7); // "apricot" has 7 characters
/// expected.insert('b', 9); // "blueberry" has 9 characters
/// assert_eq!(map, expected);
/// ```
pub fn slice_to_map<T, K, V, F>(collection: &[T], transform: F) -> HashMap<K, V>
where
K: Eq + Hash,
F: Fn(&T) -> (K, V),
{
let mut result = HashMap::with_capacity(collection.len());
for item in collection {
let (key, value) = transform(item);
result.insert(key, value);
}
result
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashMap;
#[derive(Debug, PartialEq, Clone)]
struct Person {
name: String,
age: u32,
}
#[test]
fn test_slice_to_map_integers() {
let numbers = vec![1, 2, 3, 4, 5];
let map = slice_to_map(&numbers, |&x| (x, x * x));
let mut expected = HashMap::new();
expected.insert(1, 1);
expected.insert(2, 4);
expected.insert(3, 9);
expected.insert(4, 16);
expected.insert(5, 25);
assert_eq!(map, expected);
}
#[test]
fn test_slice_to_map_strings() {
let strings = vec!["apple", "banana", "apricot", "blueberry"];
let map = slice_to_map(&strings, |s| (s.chars().next().unwrap(), s.len()));
let mut expected = HashMap::new();
expected.insert('a', 7); // "apricot" has 7 characters
expected.insert('b', 9); // "blueberry" has 9 characters
assert_eq!(map, expected);
}
#[test]
fn test_slice_to_map_with_structs() {
let people = vec![
Person {
name: "Alice".to_string(),
age: 25,
},
Person {
name: "Bob".to_string(),
age: 30,
},
Person {
name: "Charlie".to_string(),
age: 35,
},
];
let map = slice_to_map(&people, |person| (person.name.clone(), person.age));
let mut expected = HashMap::new();
expected.insert("Alice".to_string(), 25);
expected.insert("Bob".to_string(), 30);
expected.insert("Charlie".to_string(), 35);
assert_eq!(map, expected);
}
#[test]
fn test_slice_to_map_with_duplicate_keys() {
let numbers = vec![1, 2, 3, 2, 4, 3, 5];
let map = slice_to_map(&numbers, |&x| (x % 2, x));
let mut expected = HashMap::new();
expected.insert(1, 5); // Last odd number
expected.insert(0, 4); // Last even number
assert_eq!(map, expected);
}
#[test]
fn test_slice_to_map_with_empty_collection() {
let empty: Vec<i32> = vec![];
let map: HashMap<i32, i32> = slice_to_map(&empty, |&x| (x, x));
let expected: HashMap<i32, i32> = HashMap::new();
assert_eq!(map, expected);
}
#[test]
fn test_slice_to_map_with_single_element() {
let single = vec![42];
let map = slice_to_map(&single, |&x| (x, x));
let mut expected = HashMap::new();
expected.insert(42, 42);
assert_eq!(map, expected);
}
#[test]
fn test_slice_to_map_preserves_latest_value() {
let numbers = vec![10, 20, 30, 20, 10];
let map = slice_to_map(&numbers, |&x| (x / 10, x));
let mut expected = HashMap::new();
expected.insert(1, 10); // Last occurrence
expected.insert(2, 20); // Last occurrence
expected.insert(3, 30);
assert_eq!(map, expected);
}
#[test]
fn test_slice_to_map_with_optionals() {
let collection = vec![Some(1), None, Some(2), Some(1), None, Some(3), Some(2)];
let map = slice_to_map(&collection, |&x| (x, x.map(|v| v * 2)));
let mut expected = HashMap::new();
expected.insert(Some(1), Some(2)); // Last occurrence
expected.insert(None, None); // Last occurrence
expected.insert(Some(2), Some(4)); // Last occurrence
expected.insert(Some(3), Some(6));
assert_eq!(map, expected);
}
#[test]
fn test_slice_to_map_with_custom_key() {
let people = vec![
Person {
name: "Alice".to_string(),
age: 25,
},
Person {
name: "Bob".to_string(),
age: 30,
},
Person {
name: "Charlie".to_string(),
age: 35,
},
Person {
name: "Alice".to_string(),
age: 28,
},
];
let map = slice_to_map(&people, |person| (person.name.clone(), person.age));
let mut expected = HashMap::new();
expected.insert("Alice".to_string(), 28); // Last Alice
expected.insert("Bob".to_string(), 30);
expected.insert("Charlie".to_string(), 35);
assert_eq!(map, expected);
}
#[test]
fn test_slice_to_map_with_hashmap_keys() {
let collection = vec![("a", 1), ("b", 2), ("a", 3), ("c", 4)];
let map = slice_to_map(&collection, |&(k, v)| (k.to_string(), v * 2));
let mut expected = HashMap::new();
expected.insert("a".to_string(), 6);
expected.insert("b".to_string(), 4);
expected.insert("c".to_string(), 8);
assert_eq!(map, expected);
}
#[test]
fn test_slice_to_map_with_vectors_as_values() {
let collection = vec![vec![1], vec![2, 2], vec![1], vec![3, 3, 3]];
let map = slice_to_map(&collection, |v| (v.len(), v.clone()));
let mut expected = HashMap::new();
expected.insert(1, vec![1]); // Last vector with length 1
expected.insert(2, vec![2, 2]); // Last vector with length 2
expected.insert(3, vec![3, 3, 3]); // Last vector with length 3
assert_eq!(map, expected);
}
}