aboutsummaryrefslogtreecommitdiff
path: root/options/options.go
diff options
context:
space:
mode:
authorStefan Majewsky <majewsky@gmx.net>2025-04-24 10:56:48 +0200
committerStefan Majewsky <majewsky@gmx.net>2025-04-24 10:56:51 +0200
commit7e539a7d649d8e400bdaad8392fa1d6c07486376 (patch)
tree744cde81ba5fd73b1ca3ef695d093444d05625bd /options/options.go
parent23862346411fb921e1a45f25011c3db601f8591d (diff)
downloadgo-gg-7e539a7d649d8e400bdaad8392fa1d6c07486376.tar.gz
add options.Max(), options.Min()
Diffstat (limited to 'options/options.go')
-rw-r--r--options/options.go48
1 files changed, 47 insertions, 1 deletions
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]()
+ }
+}