-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.go
76 lines (63 loc) · 2.25 KB
/
api.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
// Package predicate provides predicate builders
package predicate
import (
"github.com/m4gshm/gollections/slice"
)
// Predicate tests value (converts to true or false).
type Predicate[T any] func(T) bool
// Or makes disjunction
func (p Predicate[T]) Or(or Predicate[T]) Predicate[T] { return Or(p, or) }
// And makes conjunction
func (p Predicate[T]) And(and Predicate[T]) Predicate[T] { return And(p, and) }
// Xor makes exclusive OR
func (p Predicate[T]) Xor(xor Predicate[T]) Predicate[T] { return Xor(p, xor) }
// Eq creates a predicate to test for equality
func Eq[T comparable](v T) Predicate[T] {
return func(c T) bool { return v == c }
}
// Not creates a 'not p' predicate
func Not[T any](p Predicate[T]) Predicate[T] {
return func(v T) bool { return !p(v) }
}
// And makes a conjunction of two predicates
func And[T any](p1, p2 Predicate[T]) Predicate[T] {
return func(v T) bool { return p1(v) && p2(v) }
}
// Or makes a disjunction of two predicates
func Or[T any](p1, p2 Predicate[T]) Predicate[T] {
return func(v T) bool { return p1(v) || p2(v) }
}
// Xor makes an exclusive OR of two predicates
func Xor[T any](p1, p2 Predicate[T]) Predicate[T] {
return func(v T) bool { return !(p1(v) == p2(v)) }
}
// Union applies And to predicates
func Union[T any](predicates ...Predicate[T]) Predicate[T] {
l := len(predicates)
if l == 0 {
return func(_ T) bool { return false }
} else if l == 1 {
return predicates[0]
} else if l == 2 {
return And(predicates[0], predicates[1])
}
return func(v T) bool {
for i := 0; i < len(predicates); i++ {
if !predicates[i](v) {
return false
}
}
return true
}
}
// Match creates a predicate that tests whether a value of a structure property matches a specified condition
func Match[Entity, Property any](getter func(Entity) Property, condition Predicate[Property]) Predicate[Entity] {
return func(entity Entity) bool { return condition(getter(entity)) }
}
// MatchAny creates a predicate that tests whether any value of a structure property matches a specified condition
// The property has a slice type.
func MatchAny[Entity, Property any](getter func(Entity) []Property, condition Predicate[Property]) Predicate[Entity] {
return func(entity Entity) bool {
return slice.Has(getter(entity), condition)
}
}