-
Notifications
You must be signed in to change notification settings - Fork 2
/
page.go
76 lines (64 loc) 路 1.15 KB
/
page.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 pagination
import (
"math"
)
type Page struct {
Page int
PerPage int
}
func (p Page) Offset() int {
return (p.Page - 1) * p.PerPage
}
func (p Page) Limit() int {
return p.PerPage
}
type PageResult struct {
Page int
PerPage int
TotalPages int
TotalItems int
}
func (p Page) Result(totalItems int) PageResult {
totalPage := int(math.Ceil(float64(float64(totalItems) / float64(p.PerPage))))
if totalPage == 0 {
totalPage = 1
}
page := p.Page
if page > totalPage {
page = totalPage + 1
}
return PageResult{
Page: page,
PerPage: p.PerPage,
TotalPages: totalPage,
TotalItems: totalItems,
}
}
func (p PageResult) Overflow() bool {
return p.Page > p.TotalPages
}
func (p PageResult) HasNext() bool {
return p.Page < p.TotalPages
}
func (p PageResult) Next() int {
if !p.HasNext() {
return p.Page
}
return p.Page + 1
}
func (p PageResult) HasPrevious() bool {
return p.Page > 1
}
func (p PageResult) Previous() int {
if !p.HasPrevious() {
return p.Page
}
return p.Page - 1
}
func (p PageResult) Seen() int {
seen := p.Page * p.PerPage
if seen > p.TotalItems {
return p.TotalItems
}
return seen
}