max_by

Function max_by 

Source
pub fn max_by<T, F>(collection: &[T], comparison: F) -> Option<T>
where T: Clone, F: Fn(&T, &T) -> bool,
Expand description

Find the maximum element in a collection based on a custom comparison function. If the collection is empty, returns None.

§Arguments

  • collection - A slice of items.
  • comparison - A function that takes two items and returns true if the first item is considered greater than the second.

§Returns

  • Option<T> - The maximum item in the collection based on the comparison function, or None if the collection is empty.

§Examples

use lowdash::max_by;

#[derive(Debug, PartialEq, Eq, Clone)]
struct Person {
    age: u32,
    name: String,
}

let people = vec![
    Person { age: 25, name: "Alice".to_string() },
    Person { age: 30, name: "Bob".to_string() },
    Person { age: 20, name: "Carol".to_string() },
];

let result = max_by(&people, |a, b| a.age > b.age);
assert_eq!(
    result,
    Some(Person { age: 30, name: "Bob".to_string() })
);