Skip to content

Instantly share code, notes, and snippets.

@EtienneR
Created June 29, 2017 21:42
Show Gist options
  • Save EtienneR/198d8c0a57c440ea2c261b3706d8e52b to your computer and use it in GitHub Desktop.
Save EtienneR/198d8c0a57c440ea2c261b3706d8e52b to your computer and use it in GitHub Desktop.
Paginate an array and order by descending "id"
package main
import (
"fmt"
"math"
"sort"
)
type idSorter []article
func (a idSorter) Len() int { return len(a) }
func (a idSorter) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a idSorter) Less(i, j int) bool { return a[i].id > a[j].id }
type article struct {
id int
title string
}
var perPage = 3
var articles = []article{
{1, "First"},
{2, "Second"},
{3, "Third"},
{4, "Fourth"},
{5, "Fifth"},
{6, "Sixth"},
{7, "Seventh"},
{8, "Eighth"},
{9, "Ninth"},
{10, "Tenth"},
}
func main() {
max := maxPagesPagination(len(articles))
sort.Sort(idSorter(articles))
for i := 1; i <= max; i++ {
fmt.Println(paginate(i, len(articles)))
}
/* Display result like :
[{10 Tenth} {9 Ninth} {8 Eighth}]
[{7 Seventh} {6 Sixth} {5 Fifth}]
[{4 Fourth} {3 Third} {2 Second}]
[{1 First}]
*/
}
// Return max of pages
func maxPagesPagination(total int) int {
pagesNumber := math.Ceil(float64(total) / float64(perPage))
return int(pagesNumber)
}
// Return each page content
func paginate(currentPage int, total int) []article {
firstEntry := (currentPage - 1) * perPage
lastEntry := firstEntry + perPage
if lastEntry > total {
lastEntry = total
}
return articles[firstEntry:lastEntry]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment