@@ -32,24 +32,24 @@ Output:
3232
3333// Paginator represents a set of results of pagination calculations.
3434type 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
3940}
4041
4142// New initialize a new pagination calculation and returns a Paginator as result.
4243func 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 }
5353 return p
5454}
5555
@@ -72,7 +72,7 @@ func (p *Paginator) Previous() int {
7272
7373// HasNext returns true if there is a next page relative to current page.
7474func (p * Paginator ) HasNext () bool {
75- return p .total > p .current * p .pagingNum
75+ return p .total == - 1 || p .current * p .pagingNum < p . total
7676}
7777
7878func (p * Paginator ) Next () int {
@@ -84,10 +84,7 @@ func (p *Paginator) Next() int {
8484
8585// IsLast returns true if current page is the last page.
8686func (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 ()
9188}
9289
9390// Total returns number of total rows.
@@ -97,10 +94,7 @@ func (p *Paginator) Total() int {
9794
9895// TotalPages returns number of total pages.
9996func (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
10498}
10599
106100// Current returns current page number.
@@ -134,8 +128,8 @@ func getMiddleIdx(numPages int) int {
134128// Pages returns a list of nearby page numbers relative to current page.
135129// If value is -1 means "..." that more pages are not showing.
136130func (p * Paginator ) Pages () []* Page {
137- if p .numPages == 0 {
138- return [] * Page {}
131+ if p .total == - 1 || p . numPages == 0 {
132+ return nil
139133 } else if p .numPages == 1 && p .TotalPages () == 1 {
140134 // Only show current page.
141135 return []* Page {{1 , true }}
0 commit comments