Skip to content

Commit

Permalink
Merge pull request #21 from LNOpenMetrics/dev
Browse files Browse the repository at this point in the history
utime: adding method to count occurences between timestamps
  • Loading branch information
vincenzopalazzo authored Dec 31, 2021
2 parents 426b1dc + fbe447e commit 0e39f88
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
File renamed without changes.
16 changes: 16 additions & 0 deletions utime/utime.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,19 @@ func FromDecimalUnix(decimalUnix float64) int64 {
sec, dec := math.Modf(decimalUnix)
return time.Unix(int64(sec), int64(dec*(1e9))).Unix()
}

// Count the number of occurrence that are inside the following
func OccurenceInUnixRange(from int64, to int64, step time.Duration) uint64 {
count := uint64(0)
actual := from
for actual < to {
actual = increaseTimestampByDuration(actual, step)
count++
}
return count
}

func increaseTimestampByDuration(timestamp int64, duration time.Duration) int64 {
actualTime := time.Unix(timestamp, 0).Add(duration)
return actualTime.Unix()
}
22 changes: 22 additions & 0 deletions utime/utime_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,25 @@ func TestSameInRangeMonthsUnixTwo(t *testing.T) {
t.Errorf("The two dates are inside the range of 1 month, them should be outside of this range")
}
}

func TestCountOccurenceInOneHour(t *testing.T) {
start := time.Now().Unix()
end := time.Now().Add(1 * time.Hour).Unix()

occur := OccurenceInUnixRange(start, end, 30*time.Minute)

if occur != 2 {
t.Errorf("Expected 2 by received %d", occur)
}
}

func TestCountOccurenceInOneDay(t *testing.T) {
start := time.Now().Unix()
end := time.Now().Add(24 * time.Hour).Unix()

occur := OccurenceInUnixRange(start, end, 30*time.Minute)

if occur != 2*24 {
t.Errorf("Expected %d but received %d", 2*24, occur)
}
}

0 comments on commit 0e39f88

Please sign in to comment.