reduce

Function reduce 

Source
pub fn reduce<T, R, F>(collection: &[T], accumulator: F, initial: R) -> R
where F: Fn(R, &T, usize) -> R,
Expand description

Apply a function to each item in a collection, accumulating a single result.

This function iterates over a collection 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.

§Examples

use lowdash::reduce;
let numbers = vec![1, 2, 3, 4, 5];
// Sum of all numbers
let sum = reduce(&numbers, |acc, x, _| acc + x, 0);
assert_eq!(sum, 15);
use lowdash::reduce;

#[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
let all_names = reduce(&people, |acc, person, _| format!("{} {}", acc, person.name), String::new());
assert_eq!(all_names.trim(), "Alice Bob Carol");