Skip to content

Commit

Permalink
feat: add CombineFuncs
Browse files Browse the repository at this point in the history
Signed-off-by: Manfred Touron <94029+moul@users.noreply.github.com>
  • Loading branch information
moul committed Aug 3, 2020
1 parent b51acce commit 606da10
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
13 changes: 13 additions & 0 deletions pattern.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package u

// CombineFuncs create a chain of functions.
// This can be particularly useful for creating cleanup function progressively.
// It solves the infinite loop you can have when trying to do it manually: https://play.golang.org/p/NQem8UJ500t.
func CombineFuncs(left func(), right ...func()) func() {
return func() {
left()
for _, fn := range right {
fn()
}
}
}
15 changes: 15 additions & 0 deletions pattern_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package u_test

import (
"fmt"

"moul.io/u"
)

func ExampleCombineFuncs() {
cleanup := func() { fmt.Print("A") }
cleanup = u.CombineFuncs(cleanup, func() { fmt.Print("B") })
cleanup = u.CombineFuncs(func() { fmt.Print("C") }, cleanup)
cleanup()
// Output: CAB
}

0 comments on commit 606da10

Please sign in to comment.