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
/// Calculate the product of values obtained by applying a function to each element in a collection.
/// If the collection is empty, returns 1 (multiplicative identity).
/// Works with any numeric type that implements `std::ops::Mul` and can be copied.
///
/// # Arguments
/// * `collection` - A slice of items.
/// * `iteratee` - A function that takes an item from the collection and returns a number.
///
/// # Returns
/// * `T` - The product of all numbers generated by the iteratee function.
///
/// # Examples
/// ```rust
/// use lowdash::product_by;
///
/// let numbers = vec![1, 2, 3, 4];
/// let result = product_by(&numbers, |x| x * 2);
/// assert_eq!(result, 384); // (1*2) * (2*2) * (3*2) * (4*2)
/// ```
///
/// ```rust
/// use lowdash::product_by;
///
/// #[derive(Debug)]
/// struct Rectangle {
/// width: f64,
/// height: f64,
/// }
///
/// let rectangles = vec![
/// Rectangle { width: 2.0, height: 3.0 },
/// Rectangle { width: 4.0, height: 5.0 },
/// ];
///
/// let total_area = product_by(&rectangles, |r| r.width * r.height);
/// assert_eq!(total_area, 120.0); // (2*3) * (4*5)
/// ```
pub fn product_by<T, R>(collection: &[T], iteratee: impl Fn(&T) -> R) -> R
where
R: std::ops::Mul<Output = R> + From<u8> + Copy,
{
if collection.is_empty() {
return R::from(1);
}
collection
.iter()
.fold(R::from(1), |acc, item| acc * iteratee(item))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_product_by_integers() {
let numbers = vec![1, 2, 3, 4];
let result = product_by(&numbers, |x| x * 2);
assert_eq!(result, 384);
}
#[test]
fn test_product_by_floats() {
let numbers = vec![1.5, 2.0, 3.0];
let result = product_by(&numbers, |x| x * 2.0);
assert_eq!(result, 72.0);
}
#[test]
fn test_product_by_empty() {
let empty: Vec<i32> = vec![];
let result = product_by(&empty, |x| x * 2);
assert_eq!(result, 1);
}
#[test]
fn test_product_by_with_struct() {
#[derive(Debug)]
struct Rectangle {
width: f64,
height: f64,
}
let rectangles = vec![
Rectangle {
width: 2.0,
height: 3.0,
},
Rectangle {
width: 4.0,
height: 5.0,
},
];
let total_area = product_by(&rectangles, |r| r.width * r.height);
assert_eq!(total_area, 120.0);
}
#[test]
fn test_product_by_with_zeros() {
let numbers = vec![1, 2, 0, 4];
let result = product_by(&numbers, |x| x * 2);
assert_eq!(result, 0);
}
#[test]
fn test_product_by_with_negative_numbers() {
let numbers = vec![-2, 3, -4];
let result = product_by(&numbers, |x| x * 1);
assert_eq!(result, 24);
}
#[test]
fn test_product_by_complex_transformation() {
let numbers = vec![1, 2, 3, 4];
let result = product_by(&numbers, |x| x * x);
assert_eq!(result, 576); // 1*1 * 2*2 * 3*3 * 4*4
}
}