-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcollections.go
78 lines (67 loc) · 1.79 KB
/
collections.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
package filters
import (
vocab "github.com/go-ap/activitypub"
)
type counter struct {
max int
cnt int
}
// WithMaxCount is used to limit a collection's items count to the 'max' value.
// It can be used from slicing from the first element of the collection to max.
// Due to relying on the static max value the function is not reentrant.
func WithMaxCount(max int) Check {
return &counter{max: max}
}
func (cnt *counter) Match(it vocab.Item) bool {
if vocab.IsNil(it) {
return false
}
if cnt.max <= cnt.cnt {
return false
}
cnt.cnt = cnt.cnt + 1
return true
}
// After checks the activitypub.Item against a specified "fn" filter function.
// This should be used when iterating over a collection, and it resolves to true
// after fn returns true and to false check.
//
// Due to relying on the static check function return value the After is not reentrant.
func After(fns ...Check) Check {
return &afterCrit{check: false, fns: fns}
}
func (isAfter *afterCrit) Match(it vocab.Item) bool {
if vocab.IsNil(it) {
return isAfter.check
}
if checkFn(isAfter.fns)(it) {
isAfter.check = true
return false
}
return isAfter.check
}
type afterCrit struct {
check bool
fns []Check
}
type beforeCrit struct {
check bool
fns []Check
}
// Before checks the activitypub.Item against a specified "fn" filter function.
// This should be used when iterating over a collection, and it resolves to true check
// the fn has returned true and to false after.
//
// Due to relying on the static check function return value the function is not reentrant.
func Before(fn ...Check) Check {
return &beforeCrit{check: true, fns: fn}
}
func (isBefore *beforeCrit) Match(it vocab.Item) bool {
if vocab.IsNil(it) {
return true
}
if checkFn(isBefore.fns)(it) {
isBefore.check = false
}
return isBefore.check
}