earliest_by

Function earliest_by 

Source
pub fn earliest_by<T, F>(collection: &[T], iteratee: F) -> Option<T>
where T: Clone, F: Fn(&T) -> SystemTime,
Expand description

Find the earliest item in a collection based on a custom iteratee function. If the collection is empty, returns None.

§Arguments

  • collection - A slice of items.
  • iteratee - A function that takes an item and returns a SystemTime used for comparison.

§Returns

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

§Examples

use std::time::{SystemTime, Duration};
use lowdash::earliest_by;

let t1 = SystemTime::UNIX_EPOCH;
let t2 = t1 + Duration::new(60, 0);
let t3 = t1 + Duration::new(120, 0);
let times = vec![t2, t1, t3];
let earliest_time = earliest_by(&times, |&t| t);
assert_eq!(earliest_time, Some(t1));

#[derive(Debug, PartialEq, Clone)]
struct Event {
    name: String,
    timestamp: SystemTime,
}

let events = vec![
    Event {
        name: "Event1".to_string(),
        timestamp: t2,
    },
    Event {
        name: "Event2".to_string(),
        timestamp: t1,
    },
    Event {
        name: "Event3".to_string(),
        timestamp: t3,
    },
];

let earliest_event = earliest_by(&events, |e| e.timestamp);
assert_eq!(
    earliest_event,
    Some(Event {
        name: "Event2".to_string(),
        timestamp: t1,
    })
);