Skip to content

Instantly share code, notes, and snippets.

@ismdeep
Created January 24, 2024 09:15
Show Gist options
  • Save ismdeep/93cd0d5838fbac7c5297321663c4ba41 to your computer and use it in GitHub Desktop.
Save ismdeep/93cd0d5838fbac7c5297321663c4ba41 to your computer and use it in GitHub Desktop.
pagination.go
package pagination
import "fmt"
type Pair struct {
StartIndex int64
EndIndex int64
}
func newPair(l, r int64) Pair {
return Pair{
StartIndex: l,
EndIndex: r,
}
}
func newPairSlice(pairs ...Pair) []Pair {
return pairs
}
// Pages get pagination index list
func Pages(total int64, pageSize int64, startIndex int64) []Pair {
// check total
if total <= 0 {
return nil
}
// check pageSize
if pageSize <= 0 {
panic(fmt.Sprintf("invalid parameter value: pageSize = %v", pageSize))
}
// end
if total <= pageSize {
return newPairSlice(newPair(startIndex, startIndex+total-1))
}
// head + tail
return append(
newPairSlice(newPair(startIndex, startIndex+pageSize-1)),
// recursive to get tail
Pages(total-pageSize, pageSize, startIndex+pageSize)...)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment