From f2c33dd586d5bc1369ef722024077ad639c33acc Mon Sep 17 00:00:00 2001 From: streamz Date: Mon, 27 Apr 2020 16:57:31 -0400 Subject: [PATCH] add defered param to AsyncRepeat --- README.md | 6 ++++-- hof.go | 14 ++++++++++---- hof_test.go | 27 ++++++++++++++++++++++----- 3 files changed, 36 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index aa6efbd..82dc0dc 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ Unfortunately higher order functions require the use of reflection, so they are ```golang Apply(fn F, args ...T) (func()T, error) -AsyncRepeat(fn F) func() +AsyncRepeat(fn F, defered func()) func() Compare(t0 T, t1 T, fn F) (bool, error) @@ -52,7 +52,9 @@ Reduce(initial T, t T, fn F) (T, error) // AsyncRepeat stop := AsyncRepeat(F{func() { // do something - }}) + }}, func() { + // do something defered + }) // stop doing something stop() diff --git a/hof.go b/hof.go index 279740d..27f6c41 100644 --- a/hof.go +++ b/hof.go @@ -73,15 +73,19 @@ func Apply(fn F, args ...T) (func()T, error) { // AsyncRepeat executes a Nullary F in a goroutine until result is executed" // cancel := AsyncRepeat(F{func() { // // do something -// }}) +// }}, func() { +// // defered do something +// }) // // Stop doing something // cancel() -func AsyncRepeat(fn F) func() { +func AsyncRepeat(fn F, defered func()) func() { c := make(chan _U) + cancel := func() { close(c) } - go fn.until(c) + + go fn.until(c, defered) return cancel } @@ -254,7 +258,9 @@ func (fn F) apply(args ...T) (func()T, error) { return res, nil } -func (fn F) until(c chan _U) { +func (fn F) until(c chan _U, defered func()) { + defer defered() + fn.assert(_R{_K{},_K{}}) f := reflect.ValueOf(fn.I) running := func(ch chan _U) bool { diff --git a/hof_test.go b/hof_test.go index dd17b80..9c26eca 100644 --- a/hof_test.go +++ b/hof_test.go @@ -17,8 +17,8 @@ package ginsu import ( "errors" + "sync" "testing" - "time" ) type point struct { @@ -32,16 +32,33 @@ type line struct { func TestAsyncRepeat(t *testing.T) { e := errors.New("TestAsyncRepeat Failed") count := 0 + invoked := false + + var wg0 sync.WaitGroup + wg0.Add(1) + + defered := func() { + defer wg0.Done() + invoked = true + } + + var wg1 sync.WaitGroup + wg1.Add(5) + stop := AsyncRepeat(F{func() { if count < 5 { count++ - } - }}) + wg1.Done() + } + }}, defered) + + wg1.Wait() - time.Sleep(1000 * time.Millisecond) stop() - if count != 5 { + wg0.Wait() + + if count != 5 || !invoked { t.Errorf(e.Error()) } }