-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
88 lines (73 loc) · 1.62 KB
/
main.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
package pager
import "math"
// Page ...
type Page struct {
Index int
}
// Pages ...
type Pages struct {
CurrentPage int
Pages []Page
PageCount int
ItemsPerPage int
ItemsLength int
CurrentOffset int
HasNext, HasPrev bool
PrevPage, NextPage Page
}
func calculateOffset(p *Pages) int {
switch {
case p.CurrentPage > p.PageCount:
p.CurrentPage = p.PageCount
case p.CurrentPage < 1:
p.CurrentPage = 1
}
o := (p.CurrentPage - 1) * p.ItemsPerPage
switch {
case o > p.ItemsLength:
p.CurrentPage = p.PageCount
o = calculateOffset(p)
case o < 0:
o = 0
p.CurrentPage = 1
}
return o
}
// New ...
func New(current, itemsPerPage, itemsLength int) Pages {
p := Pages{}
p.CurrentPage = current
p.ItemsPerPage = itemsPerPage
p.ItemsLength = itemsLength
d := float64(p.ItemsLength) / float64(p.ItemsPerPage)
p.PageCount = int(math.Ceil(d))
p.CurrentOffset = calculateOffset(&p)
p.HasPrev = p.CurrentPage > 1
p.HasNext = p.CurrentPage < p.PageCount
switch {
case p.HasNext:
p.NextPage = Page{p.CurrentPage + 1}
case p.HasPrev:
p.PrevPage = Page{p.CurrentPage - 1}
}
for i := 1; i <= p.PageCount; i++ {
p.Pages = append(p.Pages, Page{i})
}
return p
}
// Range return []Page within the given range
func (p Pages) Range(min, max int) []Page {
pages := []Page{}
for i := min; i <= max; i++ {
for _, page := range p.Pages {
if page.Index == i {
pages = append(pages, page)
}
}
}
return pages
}
// Margin return []Page within a given margin from the CurrentPage
func (p Pages) Margin(m int) []Page {
return p.Range(p.CurrentPage-m, p.CurrentPage+m)
}