Let debouncer delay be configurable

This commit is contained in:
2024-10-10 23:13:00 +02:00
parent dc40185002
commit 5d09d99ff5
3 changed files with 12 additions and 11 deletions

View File

@@ -7,7 +7,7 @@ type Debouncer struct {
C <-chan bool
}
func New(ch <-chan bool) *Debouncer {
func New(ch <-chan bool, window time.Duration) *Debouncer {
output := make(chan bool)
var currentState bool
var lastState bool
@@ -21,11 +21,11 @@ func New(ch <-chan bool) *Debouncer {
output <- false
lastState = false
} else {
falseTimer.Reset(200 * time.Millisecond)
falseTimer.Reset(window)
}
case v, ok := <-ch:
if !ok {
falseTimer.Reset(200 * time.Millisecond)
falseTimer.Reset(window)
<-falseTimer.C
output <- false
close(output)
@@ -35,12 +35,12 @@ func New(ch <-chan bool) *Debouncer {
if !lastState {
output <- true
lastState = true
falseTimer.Reset(200 * time.Millisecond)
falseTimer.Reset(window)
}
currentState = true
} else {
falseTimer.Reset(200 * time.Millisecond)
falseTimer.Reset(window)
currentState = false
}

View File

@@ -10,7 +10,7 @@ import (
func TestDebouncer(t *testing.T) {
t.Run("Simple", func(t *testing.T) {
ch := make(chan bool)
d := debouncer.New(ch)
d := debouncer.New(ch, 200*time.Millisecond)
go func() {
ch <- true
@@ -23,7 +23,7 @@ func TestDebouncer(t *testing.T) {
})
t.Run("TrueTrueTrueFalse", func(t *testing.T) {
ch := make(chan bool)
d := debouncer.New(ch)
d := debouncer.New(ch, 200*time.Millisecond)
go func() {
ch <- true
ch <- true
@@ -40,7 +40,7 @@ func TestDebouncer(t *testing.T) {
})
t.Run("Debounce", func(t *testing.T) {
ch := make(chan bool)
d := debouncer.New(ch)
d := debouncer.New(ch, 200*time.Millisecond)
go func() {
ch <- true
time.Sleep(10 * time.Millisecond)
@@ -65,7 +65,7 @@ func TestDebouncer(t *testing.T) {
})
t.Run("DebounceDelay", func(t *testing.T) {
ch := make(chan bool)
d := debouncer.New(ch)
d := debouncer.New(ch, 200*time.Millisecond)
go func() {
ch <- true
ch <- false