Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Pipeline #125 #127

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,7 @@ Other functional programming helpers:
- ToSlicePtr
- Empty
- Coalesce
- Pipeline

Concurrency helpers:

Expand Down Expand Up @@ -1357,6 +1358,19 @@ result, ok := lo.Coalesce[*string](nil, nilStr, &str)
// &"foobar" true
```

### Pipeline

Pipeline takes a list of functions and returns a function that takes a value as its argument and runs it through a pipeline of the original functions given in this function.
```go
cb := func(x int) int { return x * x * x }
tp := func(x int) int { return 3 * x }
db := func(x int) int { return 2 * x }
f := Pipeline(cb, tp, db)

f(5)
// 750
```

### Attempt

Invokes a function N times until it returns valid output. Returning either the caught error or nil. When first argument is less than `1`, the function runs until a sucessfull response is returned.
Expand Down
14 changes: 14 additions & 0 deletions func.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package lo

// Pipeline takes a list of functions and returns a function
// that takes a value as its argument and runs it through
// a pipeline of the original functions given in this function.
func Pipeline[T any](funcs ...func(T) T) func(T) T {
return func(t T) (result T) {
result = t
for _, f := range funcs {
result = f(result)
}
return
}
}
17 changes: 17 additions & 0 deletions func_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package lo

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestPipeline(t *testing.T) {
is := assert.New(t)

cb := func(x int) int { return x * x * x }
tp := func(x int) int { return 3 * x }
db := func(x int) int { return 2 * x }
f := Pipeline(cb, tp, db)
is.Equal(750, f(5))
}