diff --git a/condition/condition.go b/condition/condition.go index abc5259..061d8ad 100644 --- a/condition/condition.go +++ b/condition/condition.go @@ -33,6 +33,40 @@ func reflectValue(vp any) bool { } } +// And returns true if both a and b are truthy. +func And[T, U any](a T, b U) bool { + return Bool(a) && Bool(b) +} + +// Or returns false iff neither a nor b is truthy. +func Or[T, U any](a T, b U) bool { + return Bool(a) || Bool(b) +} + +// Xor returns true iff a or b but not both is truthy. +func Xor[T, U any](a T, b U) bool { + valA := Bool(a) + valB := Bool(b) + return (valA || valB) && valA != valB +} + +// Nor returns true iff neither a nor b is truthy. +func Nor[T, U any](a T, b U) bool { + return !(Bool(a) || Bool(b)) +} + +// Xnor returns true iff both a and b or neither a nor b are truthy. +func Xnor[T, U any](a T, b U) bool { + valA := Bool(a) + valB := Bool(b) + return (valA && valB) || (!valA && !valB) +} + +// Nand returns false iff both a and b are truthy. +func Nand[T, U any](a T, b U) bool { + return !Bool(a) || !Bool(b) +} + // TernaryOperator if true return trueValue else return falseValue func TernaryOperator[T any](isTrue bool, trueValue T, falseValue T) T { if isTrue { diff --git a/condition/condition_test.go b/condition/condition_test.go index 9ee4f77..821b9f9 100644 --- a/condition/condition_test.go +++ b/condition/condition_test.go @@ -62,6 +62,54 @@ func TestBool(t *testing.T) { assert.Equal(true, Bool(&ts)) } +func TestAnd(t *testing.T) { + assert := internal.NewAssert(t, "TestAnd") + assert.Equal(false, And(0, 1)) + assert.Equal(false, And(0, "")) + assert.Equal(false, And(0, "0")) + assert.Equal(true, And(1, "0")) +} + +func TestOr(t *testing.T) { + assert := internal.NewAssert(t, "TestOr") + assert.Equal(false, Or(0, "")) + assert.Equal(true, Or(0, 1)) + assert.Equal(true, Or(0, "0")) + assert.Equal(true, Or(1, "0")) +} + +func TestXor(t *testing.T) { + assert := internal.NewAssert(t, "TestOr") + assert.Equal(false, Xor(0, 0)) + assert.Equal(true, Xor(0, 1)) + assert.Equal(true, Xor(1, 0)) + assert.Equal(false, Xor(1, 1)) +} + +func TestNor(t *testing.T) { + assert := internal.NewAssert(t, "TestNor") + assert.Equal(true, Nor(0, 0)) + assert.Equal(false, Nor(0, 1)) + assert.Equal(false, Nor(1, 0)) + assert.Equal(false, Nor(1, 1)) +} + +func TestXnor(t *testing.T) { + assert := internal.NewAssert(t, "TestXnor") + assert.Equal(true, Xnor(0, 0)) + assert.Equal(false, Xnor(0, 1)) + assert.Equal(false, Xnor(1, 0)) + assert.Equal(true, Xnor(1, 1)) +} + +func TestNand(t *testing.T) { + assert := internal.NewAssert(t, "TestNand") + assert.Equal(true, Nand(0, 0)) + assert.Equal(true, Nand(0, 1)) + assert.Equal(true, Nand(1, 0)) + assert.Equal(false, Nand(1, 1)) +} + func TestTernaryOperator(t *testing.T) { assert := internal.NewAssert(t, "TernaryOperator") trueValue := "1"