golang implements paging algorithm instance code

  • 2020-06-19 10:31:30
  • OfStack

preface

This article mainly introduces the golang paging algorithm related content, share for your reference and learning, the following words do not say much, let's have a look at the detailed introduction

The sample code is as follows:


// The paging method returns the contents of the paging based on the number of pages passed, per page, total  7 A number of pages   before  1 . 2 . 3 . 4 . 5  after   Format return , Less than 5 A page returns a specific number of pages 
func Paginator(page, prepage int, nums int64) map[string]interface{} {

 var firstpage int // before 1 Page address 
 var lastpage int // after 1 Page address 
 // According to the nums The total number, and prepage Number each page   Generating total pages 
 totalpages := int(math.Ceil(float64(nums) / float64(prepage))) //page The total number of 
 if page > totalpages {
  page = totalpages
 }
 if page <= 0 {
  page = 1
 }
 var pages []int
 switch {
 case page >= totalpages-5 && totalpages > 5: // The last 5 page 
  start := totalpages - 5 + 1
  firstpage = page - 1
  lastpage = int(math.Min(float64(totalpages), float64(page+1)))
  pages = make([]int, 5)
  for i, _ := range pages {
   pages[i] = start + i
  }
 case page >= 3 && totalpages > 5:
  start := page - 3 + 1
  pages = make([]int, 5)
  firstpage = page - 3
  for i, _ := range pages {
   pages[i] = start + i
  }
  firstpage = page - 1
  lastpage = page + 1
 default:
  pages = make([]int, int(math.Min(5, float64(totalpages))))
  for i, _ := range pages {
   pages[i] = i + 1
  }
  firstpage = int(math.Max(float64(1), float64(page-1)))
  lastpage = page + 1
  //fmt.Println(pages)
 }
 paginatorMap := make(map[string]interface{})
 paginatorMap["pages"] = pages
 paginatorMap["totalpages"] = totalpages
 paginatorMap["firstpage"] = firstpage
 paginatorMap["lastpage"] = lastpage
 paginatorMap["currpage"] = page
 return paginatorMap
}

The test results are as follows


func main(){
 pageSize := 3 
 var rsCount int64 = 100
 currentPage := 8
 res := Paginator(currentPage,pageSize,rsCount)
 fmt.Println(res) 
}

The results are as follows

[

map[pages:[6 7 8 9 10] totalpages:34 firstpage:7 lastpage:9 currpage:8]

]

conclusion


Related articles: