phpify/array/array_walk.rs
1// Copyright (c) 2020 DarkWeb Design
2//
3// Permission is hereby granted, free of charge, to any person obtaining a copy
4// of this software and associated documentation files (the "Software"), to deal
5// in the Software without restriction, including without limitation the rights
6// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7// copies of the Software, and to permit persons to whom the Software is
8// furnished to do so, subject to the following conditions:
9//
10// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
11// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
12// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
13// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
14// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
15// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
16// SOFTWARE.
17
18/// Apply a user supplied function to every member of a vector
19///
20/// # Description
21///
22/// Applies the user-defined callback function to each element of the vector.
23///
24/// **callback**
25///
26/// Callback takes on two parameters. The vector parameter's value being the first, and the index
27/// second.
28///
29/// Only the values of the vector may potentially be changed, i.e., the programmer cannot add, unset
30/// or reorder elements.
31///
32/// # Examples
33///
34/// Example #1 array_walk() example
35///
36/// ```
37/// use phpify::array::array_walk;
38///
39/// let mut fruits = vec![
40/// "lemon".to_string(),
41/// "orange".to_string(),
42/// "banana".to_string(),
43/// "apple".to_string(),
44/// ];
45///
46/// fn test_alter(item: &mut String, index: usize) {
47/// *item = format!("fruit: {}", *item);
48/// }
49///
50/// array_walk(&mut fruits, test_alter);
51///
52/// assert_eq!(fruits[0], "fruit: lemon");
53/// assert_eq!(fruits[1], "fruit: orange");
54/// assert_eq!(fruits[2], "fruit: banana");
55/// assert_eq!(fruits[3], "fruit: apple");
56/// ```
57pub fn array_walk<T>(array: &mut Vec<T>, callback: impl Fn(&mut T, usize) + 'static) {
58 for (index, value) in array.iter_mut().enumerate() {
59 callback(value, index);
60 }
61}
62
63#[cfg(test)]
64mod tests {
65 use crate::array::array_walk;
66
67 #[test]
68 fn test() {
69 let mut vec = vec![1, 2, 3];
70 array_walk(&mut vec, |value, index| *value = *value * index);
71 assert_eq!(vec, [0, 2, 6]);
72 }
73}