I have been using DateTime and NaiveDateTime alot over the last year and have found that using the compare function to involves some mental gymnastics. When using compare you often just want the most recent or oldest timestamp, or else you want to sort a list of timestamps.
I am proposing four new functions for each module: earliest/2, latest/2, sort_earliest/2, and sort_latest/2. earliest/2 and latest/2 each take two DateTime structs and return the first/last time respectively. The sort_earliest/2 and sort_latest/2 functions take a list and an optional mapper, similar to the Enum.sort_by/2 function. sort_earliest/2 and sort_latest/2 will return the list in ascending/descending chronological order respectively. Example usage: ``` start_time = DateTime.earliest(datetime1, datetime2) start_time = Enum.reduce(datetime_list, &DateTime.earliest/2) sorted_times = DateTime.sort_earliest(datetime_list) sorted_records = DateTime.sort_earliest(records, &(&1.timestamp)) ``` This example is a function that uses sort_earliest to check if a time is inside a given time range: ``` def in_range(time_stamp, {start_time, end_time} = _range) do case sort_earliest([time_stamp, start_time, end_time]) do [^start_time, ^time_stamp, ^end_time] -> true _ -> false end end ``` The implementation would be something simple like this: ``` def sort_earliest(list, mapper \\ fn x -> x end) do Enum.sort_by(list, mapper, fn x, y -> :lt == DateTime.compare(x, y) end) end def earliest(%DateTime{} = datetime1, %DateTime{} = datetime2) do case DateTime.compare(datetime1, datetime2) do :gt -> datetime2 _ -> datetime1 end end ``` Might need to make sure sort_earliest is an in place sort. -- You received this message because you are subscribed to the Google Groups "elixir-lang-core" group. To unsubscribe from this group and stop receiving emails from it, send an email to elixir-lang-core+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/elixir-lang-core/47178019-74cd-44bd-b26e-4b092c5c04a2%40googlegroups.com.