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

ADDED: Nillable function #501

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
8 changes: 8 additions & 0 deletions type_manipulation.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,3 +120,11 @@ func CoalesceOrEmpty[T comparable](v ...T) T {
result, _ := Coalesce(v...)
return result
}

// Nillable return [nil] if [v] is nil, otherwise returns [fn] call result.
func Nillable[T, RT any](v *T, fn func(*T) *RT) *RT {
if IsNil(v) {
return Nil[RT]()
}
return fn(v)
}
34 changes: 34 additions & 0 deletions type_manipulation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -294,3 +294,37 @@ func TestCoalesceOrEmpty(t *testing.T) {
is.Equal(result9, struct1)
is.Equal(result10, struct1)
}

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

is.Equal(Nil[string](), Nillable(nil, func(_ *string) *string {
t.Log("unexpected call")
t.FailNow()
return nil
}))

is.Equal("foo_suffix", *Nillable(ToPtr("foo"), func(t *string) *string {
return ToPtr("foo_suffix")
}))

type type1 struct {
field1 string
}
type type2 struct {
field2 string
}

is.Equal(Nil[type1](), Nillable(nil, func(_ *type1) *type2 {
t.Log("unexpected call")
t.FailNow()
return nil
}))

input := &type1{field1: "field-value"}
want := &type2{field2: "field-value"}
is.Equal(want, *Nillable(input, func(t *type1) *type2 {
return &type2{field2: input.field1}
}))
}