diff --git a/README.md b/README.md index 20327b08..a3aef9b9 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,7 @@ and more detailed examples are here: [./examples_test.go](./examples_test.go). - [Option[T]#Take() (T, error)](https://pkg.go.dev/github.com/moznion/go-optional#Option.Take) - [Option[T]#TakeOr(fallbackValue T) T](https://pkg.go.dev/github.com/moznion/go-optional#Option.TakeOr) - [Option[T]#TakeOrElse(fallbackFunc func() T) T](https://pkg.go.dev/github.com/moznion/go-optional#Option.TakeOrElse) +- [Option[T]#OrElse(fallbackOptionValue Option[T]) Option[T]](https://pkg.go.dev/github.com/moznion/go-optional#Option.OrElse) - [Option[T]#Filter(predicate func(v T) bool) Option[T]](https://pkg.go.dev/github.com/moznion/go-optional#Option.Filter) - [Option[T]#IfSome(f func(v T))](https://pkg.go.dev/github.com/moznion/go-optional#Option.IfSome) - [Option[T]#IfSomeWithError(f func(v T) error) error](https://pkg.go.dev/github.com/moznion/go-optional#Option.IfSomeWithError) diff --git a/examples_test.go b/examples_test.go index 774fef70..6dbf2f70 100644 --- a/examples_test.go +++ b/examples_test.go @@ -550,3 +550,17 @@ func ExampleFlatMapOrWithError() { // err is nil: false // } + +func ExampleOption_OrElse() { + fallback := Some[string]("fallback") + + some := Some[string]("actual") + fmt.Printf("%s\n", some.OrElse(fallback)) + + none := None[string]() + fmt.Printf("%s\n", none.OrElse(fallback)) + + // Output: + // Some[actual] + // Some[fallback] +} diff --git a/option.go b/option.go index 67203578..bb2dd9a9 100644 --- a/option.go +++ b/option.go @@ -102,6 +102,15 @@ func (o Option[T]) TakeOrElse(fallbackFunc func() T) T { return o[value] } +// OrElse returns the Option value according to the actual value existence. +// If the receiver's Option value is Some, this function pass-through that to return. Otherwise, this value returns the `fallbackOptionValue`. +func (o Option[T]) OrElse(fallbackOptionValue Option[T]) Option[T] { + if o.IsNone() { + return fallbackOptionValue + } + return o +} + // Filter returns self if the Option has a value and the value matches the condition of the predicate function. // In other cases (i.e. it doesn't match with the predicate or the Option is None), this returns None value. func (o Option[T]) Filter(predicate func(v T) bool) Option[T] { diff --git a/option_test.go b/option_test.go index 11af1726..d338f196 100644 --- a/option_test.go +++ b/option_test.go @@ -568,3 +568,10 @@ func TestOption_String(t *testing.T) { assert.Equal(t, "Some[mystr]", Some[*MyStringer](&MyStringer{}).String()) assert.Equal(t, "None[]", None[*MyStringer]().String()) } + +func TestOption_OrElse(t *testing.T) { + fallback := Some[string]("fallback") + + assert.EqualValues(t, Some[string]("actual").OrElse(fallback).Unwrap(), "actual") + assert.EqualValues(t, None[string]().OrElse(fallback).Unwrap(), "fallback") +}