Skip to content

Commit 75dc273

Browse files
committed
feat: add Or method.
1 parent 472de8a commit 75dc273

File tree

3 files changed

+39
-0
lines changed

3 files changed

+39
-0
lines changed

error.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,5 +3,6 @@ package optional
33
import "errors"
44

55
var (
6+
ErrNilFunction = errors.New("nil function")
67
ErrNoSuchValue = errors.New("no such value")
78
)

optional.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,20 @@ func (opt *Optional[T]) IsPresent() bool {
120120
return opt.val != nil
121121
}
122122

123+
// Or returns the Optional instance if the value is present, otherwise returns an Optional produced
124+
// by the supplying function.
125+
func (opt *Optional[T]) Or(supplier func() *Optional[T]) *Optional[T] {
126+
if supplier == nil {
127+
panic(ErrNilFunction)
128+
}
129+
130+
if opt.IsPresent() {
131+
return opt
132+
}
133+
134+
return supplier()
135+
}
136+
123137
// OrElse returns the value if present, otherwise returns other.
124138
func (opt *Optional[T]) OrElse(other T) T {
125139
if opt.IsEmpty() {

optional_test.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,30 @@ func TestOptionalIsEmpty(t *testing.T) {
227227
a.NotTrueNow(opt.IsEmpty())
228228
}
229229

230+
func TestOptionalOr(t *testing.T) {
231+
a := assert.New(t)
232+
233+
opt := optional.New[string](nil)
234+
a.PanicOfNow(func() {
235+
opt.Or(nil)
236+
}, optional.ErrNilFunction)
237+
238+
out := opt.Or(func() *optional.Optional[string] { return optional.Of("or value") })
239+
a.NotNilNow(out)
240+
a.TrueNow(out.IsPresent())
241+
a.NotPanicNow(func() {
242+
a.EqualNow(out.GetPanic(), "or value")
243+
})
244+
245+
opt = optional.Of("Hello world")
246+
out = opt.Or(func() *optional.Optional[string] { return optional.Of("or value") })
247+
a.NotNilNow(out)
248+
a.TrueNow(out.IsPresent())
249+
a.NotPanicNow(func() {
250+
a.EqualNow(out.GetPanic(), "Hello world")
251+
})
252+
}
253+
230254
func TestOptionalOrElse(t *testing.T) {
231255
a := assert.New(t)
232256

0 commit comments

Comments
 (0)