Skip to content

Commit

Permalink
Add Bind #126 (#128)
Browse files Browse the repository at this point in the history
  • Loading branch information
wirekang committed Jul 3, 2022
1 parent d066df5 commit e00a624
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 0 deletions.
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,7 @@ Type manipulation helpers:
- Empty
- IsEmpty
- Coalesce
- Bind

Concurrency helpers:

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

### Bind

Returns new function that, when called, has its first argument set to the provided value.
```go
add := func(x, y int) int { return x + y }
f := Bind(add, 5)
f(10)
// 15
```

### 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 successful response is returned.
Expand Down
8 changes: 8 additions & 0 deletions func.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package lo

// Bind returns new function that, when called, has its first argument set to the provided value.
func Bind[T1, T2, R any](f func(T1, T2) R, arg1 T1) func(T2) R {
return func(t2 T2) R {
return f(arg1, t2)
}
}
16 changes: 16 additions & 0 deletions func_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package lo

import (
"testing"

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

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

add := func(x, y int) int { return x + y }
f := Bind(add, 5)
is.Equal(15, f(10))
is.Equal(0, f(-5))
}

0 comments on commit e00a624

Please sign in to comment.