@@ -32,24 +32,24 @@ Output:
32
32
33
33
// Paginator represents a set of results of pagination calculations.
34
34
type Paginator struct {
35
- total int // total rows count
36
- pagingNum int // how many rows in one page
37
- current int // current page number
38
- numPages int // how many pages to show on the UI
35
+ total int // total rows count
36
+ totalPages int
37
+ pagingNum int // how many rows in one page
38
+ current int // current page number
39
+ numPages int // how many pages to show on the UI
39
40
}
40
41
41
42
// New initialize a new pagination calculation and returns a Paginator as result.
42
43
func New (total , pagingNum , current , numPages int ) * Paginator {
43
- if pagingNum <= 0 {
44
- pagingNum = 1
45
- }
46
- if current <= 0 {
47
- current = 1
48
- }
49
- p := & Paginator {total , pagingNum , current , numPages }
50
- if p .current > p .TotalPages () {
51
- p .current = p .TotalPages ()
52
- }
44
+ pagingNum = max (pagingNum , 1 )
45
+ totalPages := (total + pagingNum - 1 ) / pagingNum
46
+ if total >= 0 {
47
+ current = min (current , totalPages )
48
+ } else {
49
+ totalPages = - 1
50
+ }
51
+ current = max (current , 1 )
52
+ p := & Paginator {total , totalPages , pagingNum , current , numPages }
53
53
return p
54
54
}
55
55
@@ -72,7 +72,7 @@ func (p *Paginator) Previous() int {
72
72
73
73
// HasNext returns true if there is a next page relative to current page.
74
74
func (p * Paginator ) HasNext () bool {
75
- return p .total > p .current * p .pagingNum
75
+ return p .total == - 1 || p .current * p .pagingNum < p . total
76
76
}
77
77
78
78
func (p * Paginator ) Next () int {
@@ -84,10 +84,7 @@ func (p *Paginator) Next() int {
84
84
85
85
// IsLast returns true if current page is the last page.
86
86
func (p * Paginator ) IsLast () bool {
87
- if p .total == 0 {
88
- return true
89
- }
90
- return p .total > (p .current - 1 )* p .pagingNum && ! p .HasNext ()
87
+ return ! p .HasNext ()
91
88
}
92
89
93
90
// Total returns number of total rows.
@@ -97,10 +94,7 @@ func (p *Paginator) Total() int {
97
94
98
95
// TotalPages returns number of total pages.
99
96
func (p * Paginator ) TotalPages () int {
100
- if p .total == 0 {
101
- return 1
102
- }
103
- return (p .total + p .pagingNum - 1 ) / p .pagingNum
97
+ return p .totalPages
104
98
}
105
99
106
100
// Current returns current page number.
@@ -134,8 +128,8 @@ func getMiddleIdx(numPages int) int {
134
128
// Pages returns a list of nearby page numbers relative to current page.
135
129
// If value is -1 means "..." that more pages are not showing.
136
130
func (p * Paginator ) Pages () []* Page {
137
- if p .numPages == 0 {
138
- return [] * Page {}
131
+ if p .total == - 1 || p . numPages == 0 {
132
+ return nil
139
133
} else if p .numPages == 1 && p .TotalPages () == 1 {
140
134
// Only show current page.
141
135
return []* Page {{1 , true }}
0 commit comments