Skip to content

Commit dba45ac

Browse files
authored
Refactored repetative code to helpers (#17)
1 parent 4ff93d6 commit dba45ac

1 file changed

Lines changed: 32 additions & 32 deletions

File tree

v2/debounce.go

Lines changed: 32 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -56,29 +56,29 @@ func Chan[T any](in <-chan T, opts ...Option) <-chan T {
5656
defer close(out)
5757

5858
var (
59-
timer *time.Timer // Timer to manage delay
60-
lastValue T // Last received value
61-
hasValue bool // Whether a value is currently pending emission
62-
count int // Number of delay resets since last emission
59+
delayTimer *time.Timer // Timer to manage delay
60+
lastValue T // Last received value
61+
hasValue bool // Whether a value is currently pending emission
62+
count int // Number of delay resets since last emission
6363
)
6464

65-
// Function to return the timer channel or nil if timer is not set
66-
// This avoids blocking on the timer channel if no timer is set
67-
timerOrNil := func() <-chan time.Time {
68-
if timer != nil {
69-
return timer.C
65+
emitLastValue := func() {
66+
if hasValue {
67+
out <- lastValue
68+
hasValue = false
69+
count = 0
70+
if delayTimer != nil {
71+
delayTimer.Stop()
72+
}
7073
}
71-
return nil
7274
}
7375

7476
for {
7577
select {
7678
case v, ok := <-in:
7779
if !ok {
7880
// Input channel closed — emit any pending value.
79-
if hasValue {
80-
out <- lastValue
81-
}
81+
emitLastValue()
8282
return
8383
}
8484

@@ -90,30 +90,30 @@ func Chan[T any](in <-chan T, opts ...Option) <-chan T {
9090

9191
// Force emit if limit reached
9292
if options.limit != 0 && count >= options.limit {
93-
out <- v
94-
hasValue = false
95-
count = 0
96-
if timer != nil {
97-
timer.Stop()
98-
}
93+
emitLastValue()
9994
continue
10095
}
10196

102-
// Start or reset the delay timer
103-
if timer == nil {
104-
timer = time.NewTimer(options.delay)
105-
} else {
106-
timer.Reset(options.delay)
107-
}
108-
case <-timerOrNil():
109-
// Delay has passed — emit the last value
110-
if hasValue {
111-
out <- lastValue
112-
hasValue = false
113-
count = 0
114-
}
97+
delayTimer = restartTimer(delayTimer, options.delay)
98+
case <-timerChanOrNil(delayTimer):
99+
emitLastValue()
115100
}
116101
}
117102
}()
118103
return out
119104
}
105+
106+
func timerChanOrNil(timer *time.Timer) <-chan time.Time {
107+
if timer != nil {
108+
return timer.C
109+
}
110+
return nil
111+
}
112+
113+
func restartTimer(timer *time.Timer, d time.Duration) *time.Timer {
114+
if timer != nil {
115+
timer.Reset(d)
116+
return timer
117+
}
118+
return time.NewTimer(d)
119+
}

0 commit comments

Comments
 (0)