-
Notifications
You must be signed in to change notification settings - Fork 1
/
slice.go
64 lines (52 loc) · 1.15 KB
/
slice.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
package paging
import (
"github.com/aserto-dev/go-directory/pkg/derr"
"github.com/pkg/errors"
"github.com/samber/lo"
)
type KeyComparer[T any] func([]string, T) bool
type KeyMapper[T any] func(T) []string
type Result[T any] struct {
Items []T
NextToken string
}
func PaginateSlice[T any](
s []T,
size int32,
token string,
keyCount int,
cmp KeyComparer[T],
mapper KeyMapper[T],
) (*Result[T], error) {
result := &Result[T]{}
start := 0
if token != "" {
cursor, err := DecodeCursor(token)
if err != nil {
return result, err
}
if len(cursor.Keys) != keyCount {
return result, derr.ErrInvalidCursor
}
_, start, _ = lo.FindIndexOf(s, func(o T) bool {
return cmp(cursor.Keys, o)
})
if start == -1 {
return result, derr.ErrInvalidCursor
}
}
pageSize := lo.Min([]int32{size, int32(len(s) - start)})
end := start + int(pageSize)
var next *string
if end < len(s) {
cursor := &Cursor{Keys: mapper(s[end])}
n, err := cursor.Encode()
if err != nil {
return result, errors.Wrap(err, "failed to encode cursor")
}
next = &n
}
result.Items = s[start:end]
result.NextToken = lo.FromPtr(next)
return result, nil
}