diff --git a/timex/timex.go b/timex/timex.go new file mode 100644 index 0000000..38d7a6d --- /dev/null +++ b/timex/timex.go @@ -0,0 +1,22 @@ +package timex + +import ( + "time" +) + +const ( + Day time.Duration = 24 * time.Hour +) + +func GenerateSeries(start, stop time.Time, interval time.Duration) []time.Time { + if start.After(stop) || interval <= 0 { + return nil + } + + l := int64(stop.Sub(start) / interval) + series := make([]time.Time, 0, l) + for t := start; !t.After(stop); t = t.Add(interval) { + series = append(series, t) + } + return series +} diff --git a/timex/timex_test.go b/timex/timex_test.go new file mode 100644 index 0000000..c318818 --- /dev/null +++ b/timex/timex_test.go @@ -0,0 +1,28 @@ +package timex + +import ( + "slices" + "testing" + "time" + + "github.com/stretchr/testify/assert" +) + +func TestGenerateSeries(t *testing.T) { + start := time.Now() + stop := start.AddDate(0, 0, 9) + + t.Run("should return nil", func(t *testing.T) { + assert.Nil(t, GenerateSeries(start, stop, 0)) + assert.Nil(t, GenerateSeries(stop, start, Day)) + }) + + t.Run("should return a series of dates", func(t *testing.T) { + actual := GenerateSeries(start, start.AddDate(0, 0, 9), Day) + expected := make([]time.Time, 10) + for i := range expected { + expected[i] = start.AddDate(0, 0, i) + } + assert.True(t, slices.EqualFunc(actual, expected, time.Time.Equal)) + }) +}