Skip to content

Instantly share code, notes, and snippets.

@mrdougwright
Last active March 25, 2020 00:39
Show Gist options
  • Save mrdougwright/8a862ce00a5535bef198866e6d0bb050 to your computer and use it in GitHub Desktop.
Save mrdougwright/8a862ce00a5535bef198866e6d0bb050 to your computer and use it in GitHub Desktop.
@spec meetup(pos_integer, pos_integer, weekday, schedule) :: :calendar.date()
def meetup(year, month, weekday, schedule) do
week = %{monday: 1, tuesday: 2, wednesday: 3, thursday: 4, friday: 5, saturday: 6, sunday: 7}
week_multi = %{first: 0, second: 1, third: 2, fourth: 3, last: 4}
{:ok, first_date} = Date.new(year, month, 1)
beg_mo = Date.day_of_week(first_date)
day = week[weekday]
# if first day of month has surpassed target day, add 7 to get to nearest day
date =
case beg_mo > day do
true ->
7 + (day - beg_mo)
false ->
day - beg_mo
end
# multiples of 7 based on schedule
date = date + 7 * week_multi[schedule]
# hack for :last day of month overage
date =
case date > 30 do
true -> date - 7
false -> date
end
{year, month, date + 1}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment