-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpredicate.go
101 lines (89 loc) · 2.54 KB
/
predicate.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package streams
// Predicate is the interface used by filtering and matching operations
//
// i.e. is used by: Stream.AllMatch, Stream.AnyMatch, Stream.Count, Stream.Filter, Stream.FirstMatch,
// Stream.LastMatch, Stream.NoneMatch and Stream.NthMatch
type Predicate[T any] interface {
// Test evaluates this predicate against the supplied value
Test(v T) bool
// And creates a composed predicate that represents a short-circuiting logical AND of this predicate and another
And(other Predicate[T]) Predicate[T]
// Or creates a composed predicate that represents a short-circuiting logical OR of this predicate and another
Or(other Predicate[T]) Predicate[T]
// Negate creates a composed predicate that represents a logical NOT of this predicate
Negate() Predicate[T]
}
// NewPredicate creates a new Predicate from the function provided
func NewPredicate[T any](f PredicateFunc[T]) Predicate[T] {
if f == nil {
return predicate[T]{
f: func(v T) bool {
return true
},
}
}
return predicate[T]{
f: f,
}
}
type predicate[T any] struct {
f PredicateFunc[T]
inner Predicate[T]
negated bool
or Predicate[T]
and Predicate[T]
}
// Test evaluates this predicate against the supplied value
func (p predicate[T]) Test(v T) bool {
var r bool
if p.f != nil {
r = p.f(v)
} else {
r = p.inner.Test(v)
}
if r && p.and != nil {
r = r && p.and.Test(v)
}
if !r && p.or != nil {
r = p.or.Test(v)
}
if p.negated {
return !r
}
return r
}
// And creates a composed predicate that represents a short-circuiting logical AND of this predicate and another
func (p predicate[T]) And(other Predicate[T]) Predicate[T] {
return predicate[T]{
inner: p,
and: other,
}
}
// Or creates a composed predicate that represents a short-circuiting logical OR of this predicate and another
func (p predicate[T]) Or(other Predicate[T]) Predicate[T] {
return predicate[T]{
inner: p,
or: other,
}
}
// Negate creates a composed predicate that represents a logical NOT of this predicate
func (p predicate[T]) Negate() Predicate[T] {
return predicate[T]{
inner: p,
negated: true,
}
}
// PredicateFunc is the function signature used to create a new Predicate
type PredicateFunc[T any] func(v T) bool
func (f PredicateFunc[T]) Test(v T) bool {
return f(v)
}
func (f PredicateFunc[T]) And(other Predicate[T]) Predicate[T] {
return NewPredicate(f).And(other)
}
func (f PredicateFunc[T]) Or(other Predicate[T]) Predicate[T] {
return NewPredicate(f).Or(other)
}
func (f PredicateFunc[T]) Negate() Predicate[T] {
return NewPredicate(f).Negate()
}