Skip to content

Commit

Permalink
refactor(helper): Rename Chain to Pipe and add Chain
Browse files Browse the repository at this point in the history
Signed-off-by: Flc゛ <four_leaf_clover@foxmail.com>
  • Loading branch information
flc1125 committed Mar 14, 2024
1 parent f0cc0a4 commit 8d60929
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 0 deletions.
37 changes: 37 additions & 0 deletions helper/helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ func With[T any](value T, callbacks ...func(T) T) T {
return value
}

// Pipe is a function that takes a value and returns a value
//
// Pipe(m1, m2, m3)(value) => m3(m2(m1(value)))
func Pipe[T any](fns ...func(T) T) func(T) T {
return func(v T) T {
for _, fn := range fns {
Expand All @@ -41,6 +44,9 @@ func Pipe[T any](fns ...func(T) T) func(T) T {
}
}

// PipeWithErr is a function that takes a value and returns a value and an error
//
// PipeWithErr(m1, m2, m3)(value) => m3(m2(m1(value)))
func PipeWithErr[T any](fns ...func(T) (T, error)) func(T) (T, error) {
var err error
return func(v T) (T, error) {
Expand All @@ -53,6 +59,37 @@ func PipeWithErr[T any](fns ...func(T) (T, error)) func(T) (T, error) {
}
}

// Chain is a reverse Pipe
//
// Chain(m1, m2, m3)(value) => m1(m2(m3(value)))
func Chain[T any](fns ...func(T) T) func(T) T {
return func(v T) T {
for i := len(fns) - 1; i >= 0; i-- {
if fns[i] != nil {
v = fns[i](v)
}
}
return v
}
}

// ChainWithErr is a reverse PipeWithErr
//
// ChainWithErr(m1, m2, m3)(value) => m1(m2(m3(value)))
func ChainWithErr[T any](fns ...func(T) (T, error)) func(T) (T, error) {
var err error
return func(v T) (T, error) {
for i := len(fns) - 1; i >= 0; i-- {
if fns[i] != nil {
if v, err = fns[i](v); err != nil {
return v, err
}
}
}
return v, nil
}
}

func When[T any](value T, condition bool, callbacks ...func(T) T) T {
if condition {
return With(value, callbacks...)
Expand Down
34 changes: 34 additions & 0 deletions helper/helper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -340,3 +340,37 @@ func TestIf(t *testing.T) {
got = If(false, "foo", "bar")
assert.Equal(t, "bar", got)
}

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

got := chain("0")
assert.Equal(t, "021", got)
}

func TestChainWithErr(t *testing.T) {
chain := ChainWithErr(func(s string) (string, error) {
return s + "1", nil
}, func(s string) (string, error) {
return s + "2", nil
})

got, err := chain("0")
assert.Nil(t, err)
assert.Equal(t, "021", got)

// with error
chain2 := ChainWithErr(func(s string) (string, error) {
return s + "1", nil
}, func(s string) (string, error) {
return s + "2", assert.AnError
})

got, err = chain2("0")
assert.Error(t, err)
assert.Equal(t, "02", got)
}

0 comments on commit 8d60929

Please sign in to comment.