Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting list of Dates in Elixir

I put together a little script to help me with an injury recovery process. It outputs what I expect, however dates do not appear to be sorting as I would expect - it looks like sorting by month/day is working, but not by year. Same result if I am only sorting a list of dates and not using a struct.

Side note, using https://github.com/lau/calendar to populate my date range.

defmodule Phase do
  defstruct day: "", weight: "" 
end

defmodule Recovery do
  alias Calendar.Date

  def phases(start_date, end_date, start_weight, increase_by) do
    # Get the range of dates
    date_range = Date.days_after_until(start_date, end_date, true) |> Enum.to_list

    # build all phases, starting at day 0
    values = do_phases(date_range, [], start_weight, increase_by)
    Enum.sort_by(values, &(&1.day))
  end

  defp do_phases([], recovery_plan, _weight, _increase_by), do: recovery_plan 
  defp do_phases([head | tail], recovery_plan, weight, increase_by) do
    v = [%Phase{day: head, weight: weight} | recovery_plan]
    do_phases(tail, v, weight + increase_by, increase_by)
  end
end

Running in iex outputs the following:

iex(18)> d1 = Date.from_erl! {2016, 12, 29}
iex(19)> d2 = Date.from_erl! {2017, 1, 19}
iex(24)> Recovery.phases(d1, d2, 30, 5)
[%Phase{day: ~D[2017-01-01], weight: 45},
 %Phase{day: ~D[2017-01-02], weight: 50},
 %Phase{day: ~D[2017-01-03], weight: 55},
 %Phase{day: ~D[2017-01-04], weight: 60},
 %Phase{day: ~D[2017-01-05], weight: 65},
 %Phase{day: ~D[2017-01-06], weight: 70},
 %Phase{day: ~D[2017-01-07], weight: 75},
 %Phase{day: ~D[2017-01-08], weight: 80},
 %Phase{day: ~D[2017-01-09], weight: 85},
 %Phase{day: ~D[2017-01-10], weight: 90},
 %Phase{day: ~D[2017-01-11], weight: 95},
 %Phase{day: ~D[2017-01-12], weight: 100},
 %Phase{day: ~D[2017-01-13], weight: 105},
 %Phase{day: ~D[2017-01-14], weight: 110},
 %Phase{day: ~D[2017-01-15], weight: 115},
 %Phase{day: ~D[2017-01-16], weight: 120},
 %Phase{day: ~D[2017-01-17], weight: 125},
 %Phase{day: ~D[2017-01-18], weight: 130},
 %Phase{day: ~D[2017-01-19], weight: 135},
 %Phase{day: ~D[2016-12-29], weight: 30},
 %Phase{day: ~D[2016-12-30], weight: 35},
 %Phase{day: ~D[2016-12-31], weight: 40}]
like image 819
Jared Knipp Avatar asked Jan 14 '17 22:01

Jared Knipp


1 Answers

The Hex docs include very useful documentation regarding sorting, including examples for dates. You don't have to pass a custom sorter function anymore, instead, you pass the Date module (or any other one that implements .compare)

dates = [~D[2019-01-01], ~D[2020-03-02], ~D[2019-06-06]]
Enum.sort(dates, Date)
like image 55
mikheevm Avatar answered Dec 04 '22 16:12

mikheevm