feature: added optional

master
amorozov 2024-06-25 12:35:10 +03:00
parent 33bc425e90
commit 7cad10126c
4 changed files with 106 additions and 0 deletions

View File

@ -4,6 +4,8 @@ import (
"errors" "errors"
"fmt" "fmt"
"slices" "slices"
"git.tswf.io/incredible-go/incredible-go-core/pkg/container/optional"
) )
func (self *ArrayList[T]) Add(element T) { func (self *ArrayList[T]) Add(element T) {
@ -190,3 +192,19 @@ func (self *ArrayList[T]) ToSlice() []T {
result := slices.Clone(self.content)[:self.size] result := slices.Clone(self.content)[:self.size]
return result return result
} }
func (self *ArrayList[T]) Find(filter func(T) bool) *optional.Optional[T] {
for index, value := range self.content {
if index >= self.size {
break
}
passed := filter(value)
if passed {
return optional.OfAny(value)
}
}
return optional.Empty[T]()
}

View File

@ -0,0 +1,6 @@
package optional
type Optional[T any] struct {
Present bool
Value T
}

View File

@ -0,0 +1,23 @@
package optional
func Empty[T any]() *Optional[T] {
return &Optional[T]{
Present: false,
}
}
func OfAny[T any](value T) *Optional[T] {
return &Optional[T]{
Present: true,
Value: value,
}
}
func OfNonDefault[T comparable](value T) *Optional[T] {
var defaultValue T
if value != defaultValue {
return Empty[T]()
} else {
return OfAny[T](value)
}
}

View File

@ -0,0 +1,59 @@
package optional
import "log"
func (self *Optional[T]) IfPresent(action func(T)) {
if self.Present {
action(self.Value)
}
}
func (self *Optional[T]) OrElsePanic(err error) T {
return self.OrElsePanicF(func() error {
return err
})
}
func (self *Optional[T]) OrElsePanicF(errorSupplier func() error) T {
if self.Present {
return self.Value
}
err := errorSupplier()
panic(err)
}
func (self *Optional[T]) OrElseFatal(err error) T {
return self.OrElseFatalF(func() error {
return err
})
}
func (self *Optional[T]) OrElseFatalF(errorSupplier func() error) T {
if self.Present {
return self.Value
}
err := errorSupplier()
var returnStub T
log.Fatal(err)
// Компилятор без return не пропустит, но сюда никогда не дойдет из-за фатала выше.
return returnStub
}
func (self *Optional[T]) OrElse(defaultValue T) T {
if self.Present {
return self.Value
}
return defaultValue
}
func (self *Optional[T]) OrElseGet(defaultValueSupplier func() T) T {
if self.Present {
return self.Value
}
return defaultValueSupplier()
}