Skip to content

Commit

Permalink
feat!(stopwatch): add WithInterval(duration) option, drop NewWithInte…
Browse files Browse the repository at this point in the history
…rval()

This also adds an Option type for arguments to New()
  • Loading branch information
meowgorithm committed Oct 31, 2024
1 parent b83d012 commit ed9d7ab
Showing 1 changed file with 21 additions and 10 deletions.
31 changes: 21 additions & 10 deletions stopwatch/stopwatch.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,19 @@ func nextID() int {
return int(atomic.AddInt64(&lastID, 1))
}

// Option is a configuration option in [New]. For example:
//
// timer := New(time.Second*10, WithInterval(5*time.Second))
type Option func(*Model)

// WithInterval is an option for setting the interval between ticks. Pass as
// an argument to [New].
func WithInterval(interval time.Duration) Option {
return func(m *Model) {
m.Interval = interval
}
}

// TickMsg is a message that is sent on every timer tick.
type TickMsg struct {
// ID is the identifier of the stopwatch that sends the message. This makes
Expand Down Expand Up @@ -47,18 +60,16 @@ type Model struct {
Interval time.Duration
}

// NewWithInterval creates a new stopwatch with the given timeout and tick
// interval.
func NewWithInterval(interval time.Duration) Model {
return Model{
Interval: interval,
id: nextID(),
// New creates a new stopwatch with 1s interval.
func New(opts ...Option) Model {
m := Model{
id: nextID(),
}
}

// New creates a new stopwatch with 1s interval.
func New() Model {
return NewWithInterval(time.Second)
for _, opt := range opts {
opt(&m)
}
return m
}

// ID returns the unique ID of the model.
Expand Down

0 comments on commit ed9d7ab

Please sign in to comment.