mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-07 06:02:27 +08:00
Add functional nor predicate (#172)
This commit is contained in:
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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!"))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user