From 7eec3798588243c493791a421e6224680870d0e2 Mon Sep 17 00:00:00 2001 From: Stefan Majewsky Date: Sat, 11 Jan 2025 12:23:31 +0100 Subject: add options.IsNoneOrZero Also, add the tests for IsSomeAnd and IsNoneOr that I forgot. --- option/option.go | 2 ++ option/option_test.go | 21 +++++++++++++++++---- 2 files changed, 19 insertions(+), 4 deletions(-) (limited to 'option') diff --git a/option/option.go b/option/option.go index 992c7b7..39fc56d 100644 --- a/option/option.go +++ b/option/option.go @@ -203,6 +203,8 @@ func (o Option[T]) IsSomeAnd(predicate func(T) bool) bool { } // IsNoneOr returns whether the Option is either empty, or contains a value that matches the given predicate. +// +// If the predicate compares against the zero value, use options.IsNoneOrZero() instead. func (o Option[T]) IsNoneOr(predicate func(T) bool) bool { return !o.isSome || predicate(o.value) } diff --git a/option/option_test.go b/option/option_test.go index 0fa255f..28e6d49 100644 --- a/option/option_test.go +++ b/option/option_test.go @@ -33,11 +33,12 @@ func TestAsSlice(t *testing.T) { AssertEqual(t, Some(42).AsSlice(), []int{42}) } -func TestFilter(t *testing.T) { - isEven := func(x int) bool { - return x%2 == 0 - } +func isEven(x int) bool { + // an example predicate for testing the various functions that take predicates + return x%2 == 0 +} +func TestFilter(t *testing.T) { AssertEqual(t, None[int]().Filter(isEven), None[int]()) AssertEqual(t, Some(41).Filter(isEven), None[int]()) AssertEqual(t, Some(42).Filter(isEven), Some(42)) @@ -48,11 +49,23 @@ func TestIsNone(t *testing.T) { AssertEqual(t, Some(42).IsNone(), false) } +func TestIsNoneOr(t *testing.T) { + AssertEqual(t, None[int]().IsNoneOr(isEven), true) + AssertEqual(t, Some(41).IsNoneOr(isEven), false) + AssertEqual(t, Some(42).IsNoneOr(isEven), true) +} + func TestIsSome(t *testing.T) { AssertEqual(t, None[int]().IsSome(), false) AssertEqual(t, Some(42).IsSome(), true) } +func TestIsSomeAnd(t *testing.T) { + AssertEqual(t, None[int]().IsSomeAnd(isEven), false) + AssertEqual(t, Some(41).IsSomeAnd(isEven), false) + AssertEqual(t, Some(42).IsSomeAnd(isEven), true) +} + func TestIsZero(t *testing.T) { AssertEqual(t, None[int]().IsZero(), true) AssertEqual(t, Some(42).IsZero(), false) -- cgit v1.2.3