Skip to content

Commit

Permalink
fix: FromNillable
Browse files Browse the repository at this point in the history
Converts receiver method to constructor method.
  • Loading branch information
levikline committed Nov 10, 2024
1 parent cdd85a1 commit e3423a4
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 9 deletions.
16 changes: 8 additions & 8 deletions option.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,14 @@ func None[T any]() Option[T] {
return map[bool]T{}
}

// FromNillable converts a nillable value to an Option.
func FromNillable[T any](v *T) Option[T] {
if v == nil {
return None[T]()
}
return Some(*v)
}

// IsSome returns whether the Option has a value or not.
func (o Option[T]) IsSome() bool {
return len(o) != 0
Expand Down Expand Up @@ -234,11 +242,3 @@ func (o *Option[T]) UnmarshalJSON(data []byte) error {
*o = Some(v)
return nil
}

// FromNillable converts a nillable value to an Option.
func (o Option[T]) FromNillable(v *T) Option[T] {
if v == nil {
return None[T]()
}
return Some(*v)
}
16 changes: 15 additions & 1 deletion option_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
"time"

"github.com/stretchr/testify/assert"
"github.com/tapp-ai/go-optional-v2"
optionalv2 "github.com/tapp-ai/go-optional-v2"
)

// Custom type for testing fmt.Stringer interface
Expand All @@ -34,6 +34,20 @@ func TestOption(t *testing.T) {
assert.True(t, optNone.IsNone())
})

// Test FromNillable method
t.Run("FromNillable", func(t *testing.T) {
var value *int = nil
opt := optionalv2.FromNillable(value)
assert.False(t, opt.IsSome())
assert.True(t, opt.IsNone())

value = new(int)
*value = 42
opt = optionalv2.FromNillable(value)
assert.True(t, opt.IsSome())
assert.Equal(t, 42, opt.Unwrap())
})

// Test Unwrap and UnwrapAsPtr methods
t.Run("UnwrapMethods", func(t *testing.T) {
optSome := optionalv2.Some("Hello")
Expand Down

0 comments on commit e3423a4

Please sign in to comment.