The following code generates a list of time slots for a period and a duration.
If a period starts at 9:00, finishes at 10:00 and the duration is 30 minutes, then I have two slots, the first starting at 9:00 and the second at 9:30.
For the same period but a duration of 15 minutes. I have 4 slots, at 9:00, 9:15, 9:30, and 9:45.
# slot.exs defmodule Slot do def to_list(_current, _last, _minutes, false), do:  def to_list(start, last, minutes, true) do stop = NaiveDateTime.add(start, minutes * 60) fits = fits?(stop, minutes, last) [start | to_list(stop, last, minutes, fits)] end def fits?(start, duration, last) do comparison = start |> NaiveDateTime.add(duration * 60) |> NaiveDateTime.compare(last) case comparison do :gt -> false :eq -> true :lt -> true end end end start = ~N[2019-09-11 09:00:00] finish = ~N[2019-09-11 10:00:00] duration = 15 IO.inspect(start, label: "start") IO.inspect(finish, label: "finish") IO.inspect(duration, label: "duration") slots = Slot.to_list( start, finish, duration, Slot.fits?(start, duration, finish) ) IO.inspect(slots, label: "slots")
How would you improve the code?
Could it be simpler?
What do you think about the variable and function names? (I am not a native english speaker)
I’ll appreciate all your comments.