Skip to content

Commit

Permalink
feat(helper): Add Chain (#134)
Browse files Browse the repository at this point in the history
Signed-off-by: Flc゛ <four_leaf_clover@foxmail.com>
  • Loading branch information
flc1125 authored Mar 6, 2024
1 parent 0956155 commit e4376a3
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
9 changes: 9 additions & 0 deletions helper/helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,15 @@ func With[T any](value T, callbacks ...func(T) T) T {
return value
}

func Chain[T any](fns ...func(T) T) func(T) T {
return func(v T) T {
for _, fn := range fns {
v = fn(v)
}
return v
}
}

func When[T any](value T, condition bool, callbacks ...func(T) T) T {
if condition {
return With(value, callbacks...)
Expand Down
37 changes: 37 additions & 0 deletions helper/helper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,43 @@ func TestWhen(t *testing.T) {
assert.Equal(t, 18, f3.Age)
}

func TestChain(t *testing.T) {
// chain functions
chain := Chain(
func(s string) string {
return s + "1"
},
func(s string) string {
return s + "2"
},
func(s string) string {
return s + "3"
},
)

assert.Equal(t, "0123", chain("0"))

// chain functions
chain2 := Chain(
func(foo *foo) *foo {
foo.Name = "bar"
return foo
},
func(foo *foo) *foo {
foo.Age = 18
return foo
},
)

f := &foo{Name: "foo"}
assert.Equal(t, "foo", f.Name)
assert.Equal(t, 0, f.Age)

got := chain2(f)
assert.Equal(t, "bar", got.Name)
assert.Equal(t, 18, got.Age)
}

func TestScan_Basic(t *testing.T) {
// string
var foo string
Expand Down

0 comments on commit e4376a3

Please sign in to comment.