2023-07-26 22:13:21 +02:00
|
|
|
package collections
|
|
|
|
|
|
|
|
import "pkg.icikowski.pl/collections/functions"
|
|
|
|
|
2024-05-28 01:28:25 +02:00
|
|
|
// Optional represents an optional value of type T.
|
2023-07-26 22:13:21 +02:00
|
|
|
type Optional[T any] struct {
|
|
|
|
e T
|
|
|
|
present bool
|
|
|
|
}
|
|
|
|
|
2024-05-28 01:28:25 +02:00
|
|
|
// IsPresent determines whether the underlying value is present.
|
2023-07-26 22:13:21 +02:00
|
|
|
func (o *Optional[T]) IsPresent() bool {
|
|
|
|
return o.present
|
|
|
|
}
|
|
|
|
|
2024-05-28 01:28:25 +02:00
|
|
|
// Get returns the underlying value.
|
2023-07-26 22:13:21 +02:00
|
|
|
func (o *Optional[T]) Get() T {
|
|
|
|
return o.e
|
|
|
|
}
|
|
|
|
|
2024-05-28 01:28:25 +02:00
|
|
|
// OrElse returns the underlying value or given value if underlying value is not present.
|
2023-07-26 22:13:21 +02:00
|
|
|
func (o *Optional[T]) OrElse(e T) T {
|
|
|
|
if !o.present {
|
|
|
|
return e
|
|
|
|
}
|
|
|
|
return o.e
|
|
|
|
}
|
|
|
|
|
2024-05-28 01:28:25 +02:00
|
|
|
// OrElseGet returns the underlying value or value from given supplier if underlying value is not present.
|
2023-07-26 22:13:21 +02:00
|
|
|
func (o *Optional[T]) OrElseGet(s functions.Supplier[T]) T {
|
|
|
|
if !o.present {
|
|
|
|
return s()
|
|
|
|
}
|
|
|
|
return o.e
|
|
|
|
}
|
|
|
|
|
2024-05-28 01:28:25 +02:00
|
|
|
// Transform transforms the underlying value with given [functions.UnaryOperator] if the vale is present.
|
2023-07-26 22:13:21 +02:00
|
|
|
func (o *Optional[T]) Transform(u functions.UnaryOperator[T]) *Optional[T] {
|
|
|
|
if o.present {
|
|
|
|
o.e = u(o.e)
|
|
|
|
}
|
|
|
|
return o
|
|
|
|
}
|
|
|
|
|
2024-05-28 01:28:25 +02:00
|
|
|
// MapOptional maps optional of type T to optional of type U using given [functions.Function].
|
2023-07-26 22:13:21 +02:00
|
|
|
func MapOptional[T, U any](src *Optional[T], mapper functions.Function[T, U]) *Optional[U] {
|
|
|
|
return &Optional[U]{mapper(src.e), src.present}
|
|
|
|
}
|