rust-lodash 0.1.0

A high-performance, type-safe Rust implementation of Lodash collection methods with zero-cost abstractions
Documentation
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
/*!

Transform methods for Lodash-RS.

This module provides transform methods like `group_by`, `key_by`, `sort_by`, etc.
These methods are used to reorganize and transform collections.
*/

use crate::collection::Collection;
// Note: These imports are kept for future use in error handling and type constraints
// use crate::utils::{LodashError, Result, ToKey, ToComparable};
use std::collections::HashMap;

/// Create an object composed of keys generated from the results of running
/// each element of collection through iteratee. The order of grouped values
/// is determined by the order they occur in collection.
/// 
/// # Examples
/// 
/// ```
/// use rust_lodash::collection::transform::group_by;
/// use std::collections::HashMap;
/// 
/// let numbers = vec![6.1, 4.2, 6.3];
/// let grouped = group_by(&numbers, |x| (*x as f64).floor() as i32);
/// assert_eq!(grouped.get(&6), Some(&vec![6.1, 6.3]));
/// assert_eq!(grouped.get(&4), Some(&vec![4.2]));
/// ```
pub fn group_by<T, K, F>(collection: &[T], iteratee: F) -> HashMap<K, Vec<T>>
where
    K: std::hash::Hash + Eq,
    T: Clone,
    F: Fn(&T) -> K,
{
    let mut groups = HashMap::new();
    for item in collection {
        let key = iteratee(item);
        groups.entry(key).or_insert_with(Vec::new).push(item.clone());
    }
    groups
}

/// Create an object composed of keys generated from the results of running
/// each element of collection through iteratee. The corresponding value of
/// each key is the last element responsible for generating the key.
/// 
/// # Examples
/// 
/// ```
/// use rust_lodash::collection::transform::key_by;
/// use std::collections::HashMap;
/// 
/// let users = vec![
///     ("john", 30),
///     ("jane", 25),
///     ("bob", 35),
/// ];
/// let keyed = key_by(&users, |(name, _)| name.to_string());
/// assert_eq!(keyed.get("john"), Some(&("john", 30)));
/// ```
pub fn key_by<T, K, F>(collection: &[T], iteratee: F) -> HashMap<K, T>
where
    K: std::hash::Hash + Eq,
    T: Clone,
    F: Fn(&T) -> K,
{
    let mut keyed = HashMap::new();
    for item in collection {
        let key = iteratee(item);
        keyed.insert(key, item.clone());
    }
    keyed
}

/// Invoke the method at path of each element in collection.
/// 
/// # Examples
/// 
/// ```
/// use rust_lodash::collection::transform::invoke;
/// 
/// let strings = vec!["hello", "world"];
/// let uppercased = invoke(&strings, |s| s.to_uppercase());
/// assert_eq!(uppercased, vec!["HELLO", "WORLD"]);
/// ```
pub fn invoke<T, U, F>(collection: &[T], method: F) -> Vec<U>
where
    F: Fn(&T) -> U,
{
    collection.iter().map(method).collect()
}

/// Create an array of elements, sorted in ascending order by the results of
/// running each element in collection through iteratee.
/// 
/// # Examples
/// 
/// ```
/// use rust_lodash::collection::transform::sort_by;
/// 
/// let users = vec![
///     ("john", 30),
///     ("jane", 25),
///     ("bob", 35),
/// ];
/// let sorted = sort_by(&users, |(_, age)| *age);
/// assert_eq!(sorted[0], ("jane", 25));
/// assert_eq!(sorted[1], ("john", 30));
/// assert_eq!(sorted[2], ("bob", 35));
/// ```
pub fn sort_by<T, K, F>(collection: &[T], iteratee: F) -> Vec<T>
where
    T: Clone,
    K: Ord,
    F: Fn(&T) -> K,
{
    let mut sorted = collection.to_vec();
    sorted.sort_by_key(iteratee);
    sorted
}

/// This method is like `sort_by` except that it allows specifying the sort
/// orders of the iteratees to sort by.
/// 
/// # Examples
/// 
/// ```
/// use rust_lodash::collection::transform::order_by;
/// 
/// let users = vec![
///     ("john", 30, "engineer"),
///     ("jane", 25, "designer"),
///     ("bob", 30, "manager"),
/// ];
/// let sorted = order_by(&users, |(_, age, _)| *age, false);
/// assert_eq!(sorted[0], ("john", 30, "engineer"));
/// assert_eq!(sorted[1], ("bob", 30, "manager"));
/// assert_eq!(sorted[2], ("jane", 25, "designer"));
/// ```
pub fn order_by<T, K, F>(collection: &[T], iteratee: F, ascending: bool) -> Vec<T>
where
    T: Clone,
    K: Ord,
    F: Fn(&T) -> K,
{
    let mut sorted = collection.to_vec();
    if ascending {
        sorted.sort_by_key(iteratee);
    } else {
        sorted.sort_by(|a, b| {
            let key_a = iteratee(a);
            let key_b = iteratee(b);
            key_b.cmp(&key_a)
        });
    }
    sorted
}

/// Collection methods that work on the `Collection` type.
impl<T> Collection<T> {
    /// Create an object composed of keys generated from the results of running
    /// each element through iteratee.
    /// 
    /// # Examples
    /// 
    /// ```
    /// use rust_lodash::collection::Collection;
    /// use std::collections::HashMap;
    /// 
    /// let collection = Collection::new(vec![6.1, 4.2, 6.3]);
    /// let grouped = collection.group_by(|x| (*x as f64).floor() as i32);
    /// assert_eq!(grouped.get(&6), Some(&vec![6.1, 6.3]));
    /// ```
    pub fn group_by<K, F>(&self, iteratee: F) -> HashMap<K, Vec<T>>
    where
        K: std::hash::Hash + Eq,
        T: Clone,
        F: Fn(&T) -> K,
    {
        group_by(&self.data, iteratee)
    }

    /// Create an object composed of keys generated from the results of running
    /// each element through iteratee.
    /// 
    /// # Examples
    /// 
    /// ```
    /// use rust_lodash::collection::Collection;
    /// use std::collections::HashMap;
    /// 
    /// let collection = Collection::new(vec![
    ///     ("john", 30),
    ///     ("jane", 25),
    ///     ("bob", 35),
    /// ]);
    /// let keyed = collection.key_by(|(name, _)| name.to_string());
    /// assert_eq!(keyed.get("john"), Some(&("john", 30)));
    /// ```
    pub fn key_by<K, F>(&self, iteratee: F) -> HashMap<K, T>
    where
        K: std::hash::Hash + Eq,
        T: Clone,
        F: Fn(&T) -> K,
    {
        key_by(&self.data, iteratee)
    }

    /// Invoke the method at path of each element.
    /// 
    /// # Examples
    /// 
    /// ```
    /// use rust_lodash::collection::Collection;
    /// 
    /// let collection = Collection::new(vec!["hello", "world"]);
    /// let uppercased = collection.invoke(|s| s.to_uppercase());
    /// assert_eq!(uppercased, vec!["HELLO", "WORLD"]);
    /// ```
    pub fn invoke<U, F>(&self, method: F) -> Vec<U>
    where
        F: Fn(&T) -> U,
    {
        invoke(&self.data, method)
    }

    /// Create an array of elements, sorted in ascending order by the results of
    /// running each element through iteratee.
    /// 
    /// # Examples
    /// 
    /// ```
    /// use rust_lodash::collection::Collection;
    /// 
    /// let collection = Collection::new(vec![
    ///     ("john", 30),
    ///     ("jane", 25),
    ///     ("bob", 35),
    /// ]);
    /// let sorted = collection.sort_by(|(_, age)| *age);
    /// assert_eq!(sorted[0], ("jane", 25));
    /// ```
    pub fn sort_by<K, F>(&self, iteratee: F) -> Vec<T>
    where
        T: Clone,
        K: Ord,
        F: Fn(&T) -> K,
    {
        sort_by(&self.data, iteratee)
    }

    /// This method is like `sort_by` except that it allows specifying the sort
    /// orders of the iteratees to sort by.
    /// 
    /// # Examples
    /// 
    /// ```
    /// use rust_lodash::collection::Collection;
    /// 
    /// let collection = Collection::new(vec![
    ///     ("john", 30, "engineer"),
    ///     ("jane", 25, "designer"),
    ///     ("bob", 30, "manager"),
    /// ]);
    /// let sorted = collection.order_by(|(_, age, _)| *age, false);
    /// assert_eq!(sorted[0], ("john", 30, "engineer"));
    /// ```
    pub fn order_by<K, F>(&self, iteratee: F, ascending: bool) -> Vec<T>
    where
        T: Clone,
        K: Ord,
        F: Fn(&T) -> K,
    {
        order_by(&self.data, iteratee, ascending)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    // use std::collections::HashMap; // Already imported at module level

    #[test]
    fn test_group_by() {
        let numbers = vec![6.1, 4.2, 6.3];
        let grouped = group_by(&numbers, |x| {
            #[allow(clippy::cast_possible_truncation, clippy::unnecessary_cast)]
            {
                (*x as f64).floor() as i32
            }
        });
        assert_eq!(grouped.get(&6), Some(&vec![6.1, 6.3]));
        assert_eq!(grouped.get(&4), Some(&vec![4.2]));
    }

    #[test]
    fn test_key_by() {
        let users = vec![
            ("john", 30),
            ("jane", 25),
            ("bob", 35),
        ];
        let keyed = key_by(&users, |(name, _)| (*name).to_string());
        assert_eq!(keyed.get("john"), Some(&("john", 30)));
        assert_eq!(keyed.get("jane"), Some(&("jane", 25)));
        assert_eq!(keyed.get("bob"), Some(&("bob", 35)));
    }

    #[test]
    fn test_invoke() {
        let strings = vec!["hello", "world"];
        let uppercased = invoke(&strings, |s| s.to_uppercase());
        assert_eq!(uppercased, vec!["HELLO", "WORLD"]);
    }

    #[test]
    fn test_sort_by() {
        let users = vec![
            ("john", 30),
            ("jane", 25),
            ("bob", 35),
        ];
        let sorted = sort_by(&users, |(_, age)| *age);
        assert_eq!(sorted[0], ("jane", 25));
        assert_eq!(sorted[1], ("john", 30));
        assert_eq!(sorted[2], ("bob", 35));
    }

    #[test]
    fn test_order_by_ascending() {
        let users = vec![
            ("john", 30),
            ("jane", 25),
            ("bob", 35),
        ];
        let sorted = order_by(&users, |(_, age)| *age, true);
        assert_eq!(sorted[0], ("jane", 25));
        assert_eq!(sorted[1], ("john", 30));
        assert_eq!(sorted[2], ("bob", 35));
    }

    #[test]
    fn test_order_by_descending() {
        let users = vec![
            ("john", 30),
            ("jane", 25),
            ("bob", 35),
        ];
        let sorted = order_by(&users, |(_, age)| *age, false);
        assert_eq!(sorted[0], ("bob", 35));
        assert_eq!(sorted[1], ("john", 30));
        assert_eq!(sorted[2], ("jane", 25));
    }

    #[test]
    fn test_collection_group_by() {
        let collection = Collection::new(vec![6.1, 4.2, 6.3]);
        let grouped = collection.group_by(|x| {
            #[allow(clippy::cast_possible_truncation, clippy::unnecessary_cast)]
            {
                (*x as f64).floor() as i32
            }
        });
        assert_eq!(grouped.get(&6), Some(&vec![6.1, 6.3]));
    }

    #[test]
    fn test_collection_key_by() {
        let collection = Collection::new(vec![
            ("john", 30),
            ("jane", 25),
            ("bob", 35),
        ]);
        let keyed = collection.key_by(|(name, _)| (*name).to_string());
        assert_eq!(keyed.get("john"), Some(&("john", 30)));
    }

    #[test]
    fn test_collection_invoke() {
        let collection = Collection::new(vec!["hello", "world"]);
        let uppercased = collection.invoke(|s| s.to_uppercase());
        assert_eq!(uppercased, vec!["HELLO", "WORLD"]);
    }

    #[test]
    fn test_collection_sort_by() {
        let collection = Collection::new(vec![
            ("john", 30),
            ("jane", 25),
            ("bob", 35),
        ]);
        let sorted = collection.sort_by(|(_, age)| *age);
        assert_eq!(sorted[0], ("jane", 25));
    }

    #[test]
    fn test_collection_order_by() {
        let collection = Collection::new(vec![
            ("john", 30),
            ("jane", 25),
            ("bob", 35),
        ]);
        let sorted = collection.order_by(|(_, age)| *age, false);
        assert_eq!(sorted[0], ("bob", 35));
    }

    #[test]
    fn test_empty_collection() {
        let empty: Vec<i32> = vec![];
        let grouped = group_by(&empty, |x| x % 2);
        assert!(grouped.is_empty());

        let keyed = key_by(&empty, std::string::ToString::to_string);
        assert!(keyed.is_empty());

        let invoked = invoke(&empty, |x| x * 2);
        assert!(invoked.is_empty());

        let sorted = sort_by(&empty, |x| *x);
        assert!(sorted.is_empty());
    }
}