latest_by

Function latest_by 

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

Returns the item from the collection for which the iteratee returns the latest SystemTime. If the collection is empty, returns the default value of T.

§Arguments

  • collection - A slice of items.
  • iteratee - A function that takes a reference to an item and returns a SystemTime.

§Returns

  • T - The item with the latest SystemTime as determined by the iteratee.
  • If the collection is empty, returns T::default().

§Examples

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

#[derive(Debug, PartialEq, Clone)]
struct Record {
    id: u32,
    timestamp: SystemTime,
}

impl Default for Record {
    fn default() -> Self {
        Record {
            id: 0,
            timestamp: SystemTime::UNIX_EPOCH,
        }
    }
}

let records = vec![
    Record {
        id: 1,
        timestamp: SystemTime::UNIX_EPOCH + Duration::new(100, 0),
    },
    Record {
        id: 2,
        timestamp: SystemTime::UNIX_EPOCH + Duration::new(200, 0),
    },
    Record {
        id: 3,
        timestamp: SystemTime::UNIX_EPOCH + Duration::new(150, 0),
    },
];

let latest_record = latest_by(&records, |r| r.timestamp);
assert_eq!(latest_record.id, 2);