pub fn reduce_right<T, R, F>(collection: &[T], accumulator: F, initial: R) -> RExpand description
Apply a function to each item in a collection, accumulating a single result from right to left.
This function iterates over a collection from the end to the start and applies the provided
accumulator function to each item along with its index and the current accumulated value.
The accumulated value is updated with each iteration based on the result of the accumulator.
§Arguments
collection- A slice of items.accumulator- A function that takes the current accumulated value, a reference to an item, and its index, then returns the new accumulated value.initial- The initial value for the accumulation.
§Returns
R- The final accumulated value after processing all items in the collection from right to left.
§Examples
use lowdash::reduce_right;
let numbers = vec![1, 2, 3, 4, 5];
// Sum of all numbers using reduce_right
let sum = reduce_right(&numbers, |acc, x, _| acc + x, 0);
assert_eq!(sum, 15);use lowdash::reduce_right;
#[derive(Debug, PartialEq)]
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: "Carol".to_string(), age: 35 },
];
// Concatenate all names in reverse order
let all_names = reduce_right(&people, |acc, person, _| {
if acc.is_empty() {
person.name.clone()
} else {
format!("{} {}", acc, person.name)
}
}, String::new());
assert_eq!(all_names, "Carol Bob Alice");