~ewintr/gte

5931868b6299d33c3b2ea7576d5bb1c98b7317ab — Erik Winter 6 months ago ee1aad1
fix overflow bug with adding months
3 files changed, 18 insertions(+), 3 deletions(-)

M internal/task/date.go
M internal/task/recur.go
M internal/task/recur_test.go
M internal/task/date.go => internal/task/date.go +9 -1
@@ 53,7 53,7 @@ type Date struct {

func NewDate(year, month, day int) Date {

	if year == 0 && month == 0 && day == 0 {
	if year == 0 || month == 0 || month > 12 || day == 0 {
		return Date{}
	}



@@ 209,6 209,14 @@ func (d Date) Add(days int) Date {
	return NewDate(year, int(month), day+days)
}

func (d Date) AddMonths(addMonths int) Date {
	year, month, day := d.t.Date()
	addYears := int((int(month) + addMonths) / 12)
	newMonth := (int(month) + addMonths) % 12

	return NewDate(year+addYears, newMonth, day)
}

func (d Date) Equal(ud Date) bool {
	return d.t.Equal(ud.Time())
}

M internal/task/recur.go => internal/task/recur.go +1 -2
@@ 268,8 268,7 @@ func (enm EveryNMonths) RecursOn(date Date) bool {
		if tDate.After(date) {
			return false
		}
		tYear, tMonth, tDay := tDate.Time().Date()
		tDate = NewDate(tYear, int(tMonth)+enm.N, tDay)
		tDate = tDate.AddMonths(enm.N)
	}

}

M internal/task/recur_test.go => internal/task/recur_test.go +8 -0
@@ 359,4 359,12 @@ func TestEveryNMonths(t *testing.T) {
			})
		}
	})

	t.Run("recurs every year", func(t *testing.T) {
		recur := task.EveryNMonths{
			Start: task.NewDate(2021, 3, 1),
			N:     12,
		}
		test.Equals(t, false, recur.RecursOn(task.NewDate(2021, 3, 9)))
	})
}