Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add time constants for Day, Week, Month, and Year #609

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,7 @@ Supported helpers for time and duration:

- [Duration](#duration)
- [Duration0 -> Duration10](#duration0---duration10)
- [Time Constants](#time-constants)

Supported helpers for channels:

Expand Down Expand Up @@ -1889,6 +1890,30 @@ str, nbr, err, duration := lo.Duration3(func() (string, int, error) {
// 3s
```

### Time Constants

Predefined time constants for easy, consistent access without repeating calculations like `24 * time.Hour`.

```go
const (
Day = 24 * time.Hour
Week = 7 * Day
Month = 30 * Day
Year = 365 * Day
)
```

Example usage:
```go
fmt.Println(lo.Day) // 24h0m0s
fmt.Println(lo.Week) // 168h0m0s
fmt.Println(lo.Month) // 720h0m0s
fmt.Println(lo.Year) // 8760h0m0s

deadline := time.Now().Add(lo.Week) // Adds 7 days
```
Using these constants helps avoid repetition and improves readability.

### ChannelDispatcher

Distributes messages from input channels into N child channels. Close events are propagated to children.
Expand Down
7 changes: 7 additions & 0 deletions time.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,13 @@ package lo

import "time"

const (
Day = 24 * time.Hour
Week = 7 * Day
Month = 30 * Day
Year = 365 * Day
)

// Duration returns the time taken to execute a function.
func Duration(cb func()) time.Duration {
return Duration0(cb)
Expand Down
10 changes: 10 additions & 0 deletions time_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,16 @@ import (
"github.com/stretchr/testify/assert"
)

func TestTimeConstants(t *testing.T) {
t.Parallel()
is := assert.New(t)

is.Equal(24*time.Hour, Day, "Day constant should be 24 hours")
is.Equal(7*Day, Week, "Week constant should be 7 days")
is.Equal(30*Day, Month, "Month constant should be 30 days")
is.Equal(365*Day, Year, "Year constant should be 365 days")
}

func TestDuration(t *testing.T) {
t.Parallel()
is := assert.New(t)
Expand Down