From 363c2522f227f4eb6185b1b2e24ce052be283749 Mon Sep 17 00:00:00 2001 From: Christian Rocha Date: Thu, 9 Apr 2020 18:21:17 -0400 Subject: [PATCH] Helper function for paginating slices --- pager/pager.go | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/pager/pager.go b/pager/pager.go index 4b4b215..79b64d1 100644 --- a/pager/pager.go +++ b/pager/pager.go @@ -49,6 +49,20 @@ func (m *Model) SetTotalPages(items int) int { return n } +// GetSliceBounds is a helper function for paginating slices. Pass the length +// of the slice you're rendering and you'll receive the start and end bounds +// corresponding the to pagination. For example: +// +// bunchOfStuff := []stuff{...} +// start, end := model.GetSliceBounds(len(bunchOfStuff)) +// sliceToRender := bunchOfStuff[start:end] +// +func (m *Model) GetSliceBounds(length int) (start int, end int) { + start = m.Page * m.PerPage + end = min(m.Page*m.PerPage+m.PerPage, length) + return start, end +} + func (m *Model) prevPage() { if m.Page > 0 { m.Page-- @@ -148,3 +162,10 @@ func dotsView(m Model) string { func arabicView(m Model) string { return fmt.Sprintf(m.ArabicFormat, m.Page+1, m.TotalPages) } + +func min(a, b int) int { + if a < b { + return a + } + return b +}