dryip 0.6.0

Short 🩸 Rust 🦀 code snippets for inspiration.
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
422
423
#![allow(clippy::cast_sign_loss)]

use std::collections::{HashMap, HashSet};

/// Check if all value in given list are equal.
///
/// Use `HashSet` to eliminate duplicate elements and then use len() to check if length is 1.
///
/// # Examples
///
/// Basic usage:
///
/// ```rust
/// # use dryip::arrays::all_equal;
/// assert!(all_equal(vec![2, 2, 2]));
/// ```
#[must_use]
pub fn all_equal(lst: Vec<u32>) -> bool {
    lst.into_iter().collect::<HashSet<u32>>().len() == 1
}

/// Check if all value in given list are unique.
///
/// - Use `HashSet` on the given vector to keep only unique occurrences.
/// - Use len() to compare the length of the unique values to the original list.
///
/// # Examples
///
/// Basic usage:
///
/// ```rust
/// # use dryip::arrays::all_unique;
/// assert!(all_unique(vec![1, 2, 3]));
/// ```
#[must_use]
pub fn all_unique(lst: Vec<u32>) -> bool {
    lst.len() == lst.into_iter().collect::<HashSet<u32>>().len()
}

/// Splits values into two groups.
///
/// If an element in `filter` is `True`, the corresponding element in the collection belongs to the first group.
/// Otherwise, it belongs to the second group.
///
/// There are two options to use here. The first is using `enumerate()` and the second is `zip()`.
/// Both should have similar code.
///
/// The other option is `partition`. However it can't work with multiple input such the current case.
/// See [`bifurcate_by`] for `partition` usage example.
///
/// # Examples
///
/// Basic usage:
///
/// ```rust
/// # use dryip::arrays::bifurcate;
///let expected: Vec<Vec<&str>> = [["beep", "boop", "bar"].to_vec(), ["foo"].to_vec()].to_vec();
///assert_eq!(
///    expected,
///    bifurcate(
///      &["beep", "boop", "foo", "bar"].to_vec(),
///      &[true, true, false, true].to_vec()
///    )
///);
/// ```
#[must_use]
pub fn bifurcate<'a>(lst: &'a [&str], filter: &'a [bool]) -> Vec<Vec<&'a str>> {
    let result1: Vec<&str> = lst
        .iter()
        .zip(filter)
        .filter(|(_, lst2)| **lst2)
        .map(|(lst1, _)| *lst1)
        .collect();

    let result2: Vec<&str> = lst
        .iter()
        .zip(filter)
        .filter(|(_, lst2)| !**lst2)
        .map(|(lst1, _)| *lst1)
        .collect();

    [result1, result2].to_vec()
}

/// Splits values into two groups according to a passed function.
///
/// Which specifies which group an element in the input list belongs to.
/// If the function returns True, the element belongs to the first group; otherwise, it belongs to the second group.
///
/// Use list comprehension to add elements to groups, based on fn.
///
/// # Examples
///
/// Basic usage:
///
/// ```rust
/// # use dryip::arrays::bifurcate_by;
///fn starts_with(item: &str) -> bool {
///      item.starts_with('b')
///}
///
///let expected: Vec<Vec<&str>> = [["beep", "boop", "bar"].to_vec(), ["foo"].to_vec()].to_vec();
///assert_eq!(
///    expected,
///    bifurcate_by(&["beep", "boop", "foo", "bar"].to_vec(), &starts_with)
///);
/// ```
#[must_use]
pub fn bifurcate_by<'a>(lst: &[&'a str], f: &'a dyn Fn(&str) -> bool) -> Vec<Vec<&'a str>> {
    let (result, result1): (Vec<&str>, Vec<&str>) = lst.iter().partition(|item| f(item));

    [result, result1].to_vec()
}

/// Chunks a list into smaller lists of a specified size.
///
/// Rust `slice` has built-in `chucks()` function.
/// But it returns a slice. So you need to iterate the slice and convert
/// them into a vector.
///
/// # Examples
///
/// Basic usage:
///
/// ```rust
/// # use dryip::arrays::chunk;
///let input = vec![1, 2, 3, 4, 5];
///let expected = vec![vec![1, 2], vec![3, 4], vec![5]];
///assert_eq!(expected, chunk(&input, 2));
/// ```
#[must_use]
pub fn chunk(lst: &[i32], size: usize) -> Vec<Vec<i32>> {
    lst.chunks(size).into_iter().map(<[i32]>::to_vec).collect()
}

/// Removes falsey values from a list.
///
/// We have `Option` type in Rust. This is the recomended type to use
/// in this case.
///
/// # Examples
///
/// Basic usage:
///
/// ```rust
/// # use dryip::arrays::compact;
///let input = vec![None, Some(1), None, None];
///let expected = vec![Some(1)];
///assert_eq!(expected, compact(input));
/// ```
#[must_use]
pub fn compact(lst: Vec<Option<i32>>) -> Vec<Option<i32>> {
    lst.into_iter().filter(<Option<i32>>::is_some).collect()
}

/// Groups the elements of a list based on the given function.
///
/// Groups the elements of a list based on the given function and returns the count of elements in each group.
///
/// The function signature is similar to [`bifurcate_by`].
/// It uses `HashMap`'s `entry()` to update the previous result.
///
/// # Examples
///
/// Basic usage:
/// ```
/// # use std::collections::HashMap;
/// # use dryip::arrays::count_by;
///fn len(item: &str) -> i32 {
///    item.len() as i32
///}
///let expected = HashMap::from([(3, 2), (5, 1)]);
///let input = vec!["one", "two", "three"];
///assert_eq!(expected, count_by(input, &len));
///```
pub fn count_by(lst: Vec<&str>, f: &dyn Fn(&str) -> i32) -> HashMap<i32, i32> {
    let mut result = HashMap::new();
    for item in lst {
        let prev = result.entry(f(item)).or_insert(0);
        *prev += 1;
    }
    result
}

/// Counts occurrences
///
/// Counts the occurrences of a value in a vector.
///
/// Increment a counter for every item in the vector that has the given value and is of the same type.
/// Using [`std::iter::Iterator::fold`] will make our code shorter.
///
/// # Examples
///
/// Basic usage:
///
/// ```rust
/// # use dryip::arrays::count_occurrences;
/// let input = vec![1, 1, 2, 1, 2, 3];
/// assert_eq!(3, count_occurrences(&input, 1));
/// ```
///
/// # Alternatives:
///
/// Using [`std::iter::Iterator::count`]
///
/// ```rust
/// fn count_occurrences(lst: &[i32], val: i32) -> i32 {
///    lst.iter().filter(|&&x| x == val).count() as i32
/// }
///
/// let input = vec![1, 1, 2, 1, 2, 3];
/// assert_eq!(3, count_occurrences(&input, 1));
/// ```
#[must_use]
pub fn count_occurrences(lst: &[i32], val: i32) -> i32 {
    lst.iter()
        .fold(0, |acc, &x| if x == val { acc + 1 } else { acc })
}

/// Deep flattens a list.
///
/// `slice` has a built in [`std::iter::Iterator::flatten`]
///
/// # Examples
///
/// Basic usage:
///
/// ```rust
/// # use dryip::arrays::deep_flatten;
/// let input = vec![vec![1], vec![2], vec![3, 4], vec![5]];
/// let expected = vec![1, 2, 3, 4, 5];
/// assert_eq!(expected, deep_flatten(input));
/// ```
#[must_use]
pub fn deep_flatten(lst: Vec<Vec<i32>>) -> Vec<i32> {
    lst.into_iter().flatten().collect()
}

/// Difference
///
/// Returns the difference between two iterables.
///
/// - Convert b slice to [`use std::collections::HashSet`] to remove duplicates.
/// - Iterate over a and keep the values not contained in b using [`std::iter::Iterator::filter`]
#[must_use]
pub fn difference(a: &[i32], b: &[i32]) -> Vec<i32> {
    let b: HashSet<_> = b.iter().copied().collect();
    a.iter().filter(|x| !b.contains(x)).copied().collect()
}

/// Every
///
/// Returns True if the provided function returns True for every element in the vector, False otherwise.
///
/// Use [`std::iter::Iterator::any`] to tests if any element of the iterator matches a predicate.
///
/// # Examples
///
/// Basic usage:
///
/// ```rust
/// # use dryip::arrays::every;
/// fn bigger(item: i32) -> bool {
///     item > 1
/// }
///
/// let input = &[4, 2, 3];
/// assert_eq!(true, every(input, &bigger));
/// ````
pub fn every(lst: &[i32], f: &dyn Fn(i32) -> bool) -> bool {
    lst.iter().any(|&x| f(x))
}

/// Every Nth
///
/// Returns every nth element in a list.
///
/// The python version use `lst[nth-1::nth]` wich will start from the index `nth-1`.
/// You can use [`std::iter::Iterator::skip`] to replicate this behavior.
///
/// # Examples
///
/// Basic usage:
///
/// ```rust
/// # use dryip::arrays::every_nth;
/// let input = vec![1, 2, 3, 4, 5, 6];
/// let expected = vec![2, 4, 6];
/// assert_eq!(expected, every_nth(input, 2));
/// ````
#[must_use]
pub fn every_nth(lst: Vec<i32>, nth: usize) -> Vec<i32> {
    lst.into_iter().skip(nth - 1).step_by(nth).collect()
}

/// Returns a list of numbers in the arithmetic progression starting with the
/// given positive integer and up to the specified limit.
///
/// Use [Range] to and increment it using `step_by()`
///
/// # Examples
///
/// Basic usage:
///
/// ```rust
/// # use dryip::arrays::arithmetic_progression;
/// assert_eq!([5, 10, 15, 20, 25].to_vec(), arithmetic_progression(5, 25));
/// ```
/// [Range]: https://doc.rust-lang.org/std/ops/struct.Range.html
#[must_use]
pub fn arithmetic_progression(n: i32, lim: i32) -> Vec<i32> {
    (n..=lim).step_by(n as usize).collect::<Vec<i32>>()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_all_equal() {
        assert!(all_equal(vec![1, 1, 1, 1]));
        assert!(!all_equal(vec![1, 2, 3, 4, 5, 6]));
    }
    #[test]
    fn test_all_unique() {
        assert!(all_unique(vec![1, 2, 3, 4, 5, 6]));
        assert!(!all_unique(vec![1, 2, 2, 3, 4, 5]));
    }
    #[test]
    fn test_bifurcate() {
        let expected: Vec<Vec<&str>> = vec![vec!["beep", "boop", "bar"], vec!["foo"]];
        assert_eq!(
            expected,
            bifurcate(
                ["beep", "boop", "foo", "bar"].as_ref(),
                [true, true, false, true].as_ref()
            )
        );
    }
    #[test]
    fn test_bifurcate_by() {
        fn starts_with(item: &str) -> bool {
            item.starts_with('b')
        }

        let expected: Vec<Vec<&str>> = vec![vec!["beep", "boop", "bar"], vec!["foo"]];
        assert_eq!(
            expected,
            bifurcate_by(["beep", "boop", "foo", "bar"].as_ref(), &starts_with)
        );
    }
    #[test]
    fn test_chunk() {
        let input = vec![1, 2, 3, 4, 5];
        let expected = vec![vec![1, 2], vec![3, 4], vec![5]];
        assert_eq!(expected, chunk(&input, 2));

        let input = vec![1, 2, 3, 4, 5];
        let expected = vec![vec![1], vec![2], vec![3], vec![4], vec![5]];
        assert_eq!(expected, chunk(&input, 1));

        let input = vec![1, 2, 3, 4, 5];
        let expected = vec![vec![1, 2, 3, 4, 5]];
        assert_eq!(expected, chunk(&input, 5));
    }
    #[test]
    fn test_compact() {
        let input = vec![None, Some(1), None, None];
        let expected = vec![Some(1)];
        assert_eq!(expected, compact(input));
    }
    #[test]
    fn test_count_by() {
        fn len(item: &str) -> i32 {
            item.len() as i32
        }
        let expected = HashMap::from([(3, 2), (5, 1)]);
        let input = vec!["one", "two", "three"];
        assert_eq!(expected, count_by(input, &len));
    }
    #[test]
    fn test_count_occurences() {
        let input = vec![1, 1, 2, 1, 2, 3];
        assert_eq!(3, count_occurrences(&input, 1));

        let input = vec![0, 100, 2, 1, 2, 3];
        assert_eq!(1, count_occurrences(&input, 0));
    }
    #[test]
    fn test_deep_flatten() {
        let input = vec![vec![1], vec![2], vec![3, 4], vec![5]];
        let expected = vec![1, 2, 3, 4, 5];
        assert_eq!(expected, deep_flatten(input));

        let input = vec![vec![1, 2, 3, 4], vec![5, 6]];
        let expected = vec![1, 2, 3, 4, 5, 6];
        assert_eq!(expected, deep_flatten(input));
    }
    #[test]
    fn test_difference() {
        let (a, b) = (&[1, 2, 3], &[1, 2, 4]);
        assert_eq!(vec![3], difference(a, b));
    }
    #[test]
    fn test_every() {
        fn bigger(item: i32) -> bool {
            item > 1
        }
        let input = &[4, 2, 3];
        assert_eq!(true, every(input, &bigger));
    }
    #[test]
    fn test_every_nth() {
        let input = vec![1, 2, 3, 4, 5, 6];
        let expected = vec![2, 4, 6];
        assert_eq!(expected, every_nth(input, 2));
    }
    #[test]
    fn test_arithmetic_progression() {
        assert_eq!(vec![5, 10, 15, 20, 25], arithmetic_progression(5, 25));
        assert_eq!(vec![2, 4, 6, 8, 10], arithmetic_progression(2, 10));
    }
}