Skip to content

Commit

Permalink
feat: add time extensions
Browse files Browse the repository at this point in the history
  • Loading branch information
francesconi committed Aug 23, 2024
1 parent 1c2890c commit 7813c87
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
22 changes: 22 additions & 0 deletions timex/timex.go
Original file line number Diff line number Diff line change
@@ -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
}
28 changes: 28 additions & 0 deletions timex/timex_test.go
Original file line number Diff line number Diff line change
@@ -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))
})
}

0 comments on commit 7813c87

Please sign in to comment.