From cd156dba5f1e0b850d81be1c2ba7e570377f6977 Mon Sep 17 00:00:00 2001 From: donutloop Date: Wed, 21 Feb 2024 03:05:54 +0100 Subject: [PATCH] Add functional nor predicate (#172) --- function/predicate.go | 13 +++++++++++++ function/predicate_test.go | 23 +++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/function/predicate.go b/function/predicate.go index 0d1acf3..c503b43 100644 --- a/function/predicate.go +++ b/function/predicate.go @@ -32,3 +32,16 @@ func Or[T any](predicates ...func(T) bool) func(T) bool { return false // False if all predicates are false } } + +// Nor returns a composed predicate that represents the logical NOR of a list of predicates. +// It evaluates to true only if all predicates evaluate to false for the given value. +func Nor[T any](predicates ...func(T) bool) func(T) bool { + return func(value T) bool { + for _, predicate := range predicates { + if predicate(value) { + return false // If any predicate evaluates to true, the NOR result is false + } + } + return true // Only returns true if all predicates evaluate to false + } +} diff --git a/function/predicate_test.go b/function/predicate_test.go index 6ceb6f6..b0154d6 100644 --- a/function/predicate_test.go +++ b/function/predicate_test.go @@ -54,6 +54,26 @@ func TestPredicatesAndPure(t *testing.T) { assert.ShouldBeFalse(isNumericAndLength5("abcde")) } +func TestPredicatesNorPure(t *testing.T) { + t.Parallel() + + assert := internal.NewAssert(t, "TestPredicatesNorPure") + + match := Nor( + func(s string) bool { return strings.ContainsAny(s, "0123456789") }, + func(s string) bool { return len(s) == 5 }, + ) + + assert.ShouldBeTrue(match("dbcdckkeee")) + + match = Nor( + func(s string) bool { return strings.ContainsAny(s, "0123456789") }, + func(s string) bool { return len(s) == 5 }, + ) + + assert.ShouldBeFalse(match("0123456789")) +} + func TestPredicatesMix(t *testing.T) { t.Parallel() @@ -72,4 +92,7 @@ func TestPredicatesMix(t *testing.T) { c := Negate(And(a, b)) assert.ShouldBeFalse(c("hello!")) + + c = Nor(a, b) + assert.ShouldBeFalse(c("hello!")) }