pagination.go 1003 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package pagination
  2. import "math"
  3. type Data struct {
  4. currentPage int64
  5. maxPages int64
  6. resultsCount int64
  7. resultsPerPage int64
  8. }
  9. func New(currentPage, resultsCount, resultsPerPage int64) *Data {
  10. maxPages := int64(1)
  11. if resultsCount > 0 {
  12. maxPages = int64(
  13. math.Ceil(
  14. float64(resultsCount) / float64(resultsPerPage),
  15. ),
  16. )
  17. }
  18. if currentPage < 1 {
  19. currentPage = 1
  20. } else if currentPage > maxPages {
  21. currentPage = maxPages
  22. }
  23. return &Data{
  24. currentPage: currentPage,
  25. maxPages: maxPages,
  26. resultsCount: resultsCount,
  27. resultsPerPage: resultsPerPage,
  28. }
  29. }
  30. func (d *Data) CurrentPage() int64 {
  31. return d.currentPage
  32. }
  33. func (d *Data) MaxPages() int64 {
  34. return d.maxPages
  35. }
  36. func (d *Data) ResultsCount() int64 {
  37. return d.resultsCount
  38. }
  39. func (d *Data) ResultsPerPage() int64 {
  40. return d.resultsPerPage
  41. }
  42. // Returns [LIMIT, OFFSET]
  43. func (d *Data) Limit() (int64, int64) {
  44. return d.resultsPerPage, d.currentPage*d.resultsPerPage - d.resultsPerPage
  45. }