From 7e539a7d649d8e400bdaad8392fa1d6c07486376 Mon Sep 17 00:00:00 2001 From: Stefan Majewsky Date: Thu, 24 Apr 2025 10:56:48 +0200 Subject: add options.Max(), options.Min() --- options/options.go | 48 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) (limited to 'options/options.go') diff --git a/options/options.go b/options/options.go index bfae710..110b212 100644 --- a/options/options.go +++ b/options/options.go @@ -8,7 +8,11 @@ // that cannot be expressed as methods on the Option type itself. package options -import . "github.com/majewsky/gg/option" +import ( + "cmp" + + . "github.com/majewsky/gg/option" +) // NOTE: Keep functions sorted by name. @@ -37,3 +41,45 @@ func Map[T, U any](o Option[T], mapping func(T) U) Option[U] { return None[U]() } } + +// Max returns the largest of its input values, while disregarding None values. +// If there are no Some values, None is returned. +func Max[T cmp.Ordered](inputs ...Option[T]) Option[T] { + var ( + result T + isSome = false + ) + for _, i := range inputs { + value, ok := i.Unpack() + if ok && (!isSome || result < value) { + result = value + isSome = true + } + } + if isSome { + return Some(result) + } else { + return None[T]() + } +} + +// Min returns the smallest of its input values, while disregarding None values. +// If there are no Some values, None is returned. +func Min[T cmp.Ordered](inputs ...Option[T]) Option[T] { + var ( + result T + isSome = false + ) + for _, i := range inputs { + value, ok := i.Unpack() + if ok && (!isSome || result > value) { + result = value + isSome = true + } + } + if isSome { + return Some(result) + } else { + return None[T]() + } +} -- cgit v1.2.3