From d651c6fb097d5b7e6cd08946172e31e355c4c9dd Mon Sep 17 00:00:00 2001 From: nikkiing <1031497516@qq.com> Date: Wed, 19 Apr 2023 17:07:26 +0800 Subject: [PATCH] PageToSlice --- pagination/v1/pagination.go | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/pagination/v1/pagination.go b/pagination/v1/pagination.go index 089a284..e880d6a 100644 --- a/pagination/v1/pagination.go +++ b/pagination/v1/pagination.go @@ -21,6 +21,36 @@ type Integer interface { ~int | ~int32 } +// 用于对一个切片分页 +func PageToSlice[T ~int](page, pageSize, total T) (begin, end T) { + if page < DefaultPage { + page = DefaultPage + } + + if pageSize <= MinPageSize { + pageSize = MinPageSize + } + + if pageSize >= MaxPageSize { + pageSize = MaxPageSize + } + + // 计算总页数 + totalPage := (total / pageSize) + 1 + if page > totalPage { + page = totalPage + } + + begin = (page - 1) * pageSize + if total-begin <= pageSize { + end = total + } else { + end = begin + pageSize + } + return +} + +// 用于分页查询 func PageToOffset[T Integer](page, pageSize T) (offset, limit T) { if page < DefaultPage { page = DefaultPage