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 Identity function #420

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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,7 @@ Type manipulation helpers:
- [IsEmpty](#isempty)
- [IsNotEmpty](#isnotempty)
- [Coalesce](#coalesce)
- [Identity](#identity)

Function helpers:

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

### Identity

Returns the argument itself.
```go
lo.Identity(42)
// 42

lo.Identity("foobar")
// "foobar"
```

### Partial

Returns new function that, when called, has its first argument set to the provided value.
Expand Down
5 changes: 5 additions & 0 deletions type_manipulation.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,3 +106,8 @@ func Coalesce[T comparable](v ...T) (result T, ok bool) {

return
}

// Identity returns the argument itself.
func Identity[T any](v T) T {
return v
}
20 changes: 20 additions & 0 deletions type_manipulation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -233,3 +233,23 @@ func TestCoalesce(t *testing.T) {
is.Equal(result10, struct1)
is.True(ok10)
}

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

is.Equal(Identity[int](42), 42)
is.Equal(Identity[string]("foobar"), "foobar")
is.Equal(Identity[bool](true), true)
is.Equal(Identity[bool](false), false)
is.Equal(Identity[error](assert.AnError), assert.AnError)
is.Equal(Identity[interface{}]("foobar"), "foobar")
is.Equal(Identity[interface{}](42), 42)
is.Equal(Identity[interface{}](true), true)
is.Equal(Identity[interface{}](false), false)
is.Equal(Identity[interface{}](assert.AnError), assert.AnError)
is.Equal(Identity[interface{}](nil), nil)
is.Equal(Identity[interface{}]([]int{1, 2, 3}), []int{1, 2, 3})
is.Equal(Identity[interface{}](map[int]string{1: "foo", 2: "bar"}), map[int]string{1: "foo", 2: "bar"})
is.Equal(Identity[interface{}](struct{ foo string }{foo: "bar"}), struct{ foo string }{foo: "bar"})
}