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