I'm trying to figure out the most efficient way to find the closest payday from a given date.
Let's say we know payday are every 14 days and that January 6, 2022 was one of them. What is the most efficient way to find the next payday for a given date (the date is the beginning of a week actually) from a known payday?
Here is a current working ugly implementation
def payday_first_date
# TODO: Very reliable, but very inefficient
@payday_first_date ||= begin
date = known_pay_day
date -= 14.days until date < given_date
date += 14.days until date > given_date
date
end
end
def known_pay_day
# Thursday January 6, 2022 was a payday
@known_pay_day ||= Date.new(2022, 2, 17)
end
The given_date could be in the future and also in the past. It can be a date from another year aswell.
Thanks in advance!