Created
January 24, 2024 09:15
-
-
Save ismdeep/93cd0d5838fbac7c5297321663c4ba41 to your computer and use it in GitHub Desktop.
pagination.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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