Skip to content

Commit

Permalink
Merge pull request #222 from vaskoz/day105
Browse files Browse the repository at this point in the history
Day105
  • Loading branch information
vaskoz committed Dec 6, 2018
2 parents d8d33bc + a4e72f4 commit 6adc4c2
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,3 +114,4 @@ problems from
* [Day 102](https://github.com/vaskoz/dailycodingproblem-go/issues/214)
* [Day 103](https://github.com/vaskoz/dailycodingproblem-go/issues/217)
* [Day 104](https://github.com/vaskoz/dailycodingproblem-go/issues/219)
* [Day 105](https://github.com/vaskoz/dailycodingproblem-go/issues/221)
15 changes: 15 additions & 0 deletions day105/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package day105

import "time"

// Debounced returns a debounced function that will not call its
// provided function until after N milliseconds despite calling it.
func Debounced(f func(), N int) func() {
created := time.Now()
return func() {
now := time.Now()
if elapsed := int(now.Sub(created) / time.Millisecond); elapsed > N {
f()
}
}
}
28 changes: 28 additions & 0 deletions day105/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package day105

import (
"testing"
"time"
)

func TestDebounced(t *testing.T) {
t.Parallel()
x := 0
f := func() {
x++
}
dbf := Debounced(f, 500)
for i := 0; i < 10; i++ {
dbf()
}
if x != 0 {
t.Errorf("Expected x not to change since it's debounced for 500ms")
}
time.Sleep(800 * time.Millisecond)
for i := 0; i < 10; i++ {
dbf()
}
if x != 10 {
t.Errorf("Expected x to be incremented 10 times")
}
}

0 comments on commit 6adc4c2

Please sign in to comment.