You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
68 lines
1.4 KiB
Go
68 lines
1.4 KiB
Go
package page
|
|
|
|
import "fmt"
|
|
|
|
// PaginationMemory 内存分页
|
|
type PaginationMemory[T any] struct {
|
|
*Pagination // 分页参数
|
|
Data []T // 数据
|
|
}
|
|
|
|
// NewMemoryPagination 构建内存分页器
|
|
func NewMemoryPagination[T any](size int, data []T) *PaginationMemory[T] {
|
|
tmp := &PaginationMemory[T]{
|
|
Pagination: &Pagination{
|
|
Size: int64(size),
|
|
Total: int64(len(data)),
|
|
Current: 0,
|
|
},
|
|
Data: data,
|
|
}
|
|
return tmp
|
|
}
|
|
|
|
// DefaultMemoryPagination 默认内存分页器
|
|
func DefaultMemoryPagination[T any]() *PaginationMemory[T] {
|
|
t := make([]T, 0)
|
|
return NewMemoryPagination(DefaultPageSize, t)
|
|
}
|
|
|
|
// WithData 设置Data
|
|
func (p *PaginationMemory[T]) WithData(data []T) *PaginationMemory[T] {
|
|
p.Data = data
|
|
p.Total = int64(len(p.Data))
|
|
return p
|
|
}
|
|
|
|
// NextPage 返回下一页数据
|
|
func (p *PaginationMemory[T]) NextPage() []T {
|
|
p.Pagination.NextPage()
|
|
|
|
return p.currentData()
|
|
}
|
|
|
|
// currentData 返回当前页数据
|
|
func (p *PaginationMemory[T]) currentData() []T {
|
|
start := (p.Current - 1) * p.Size
|
|
end := p.Current * p.Size
|
|
|
|
dataLen := len(p.Data)
|
|
if dataLen < int(end) {
|
|
end = int64(dataLen)
|
|
}
|
|
|
|
return p.Data[start:end]
|
|
}
|
|
|
|
// PrevPage 返回上一页数据
|
|
func (p *PaginationMemory[T]) PrevPage() []T {
|
|
// 减一页
|
|
p.Pagination.PrevPage()
|
|
|
|
return p.currentData()
|
|
}
|
|
|
|
func (p *PaginationMemory[T]) String() string {
|
|
return fmt.Sprintf("%s\nData: %v", p.Pagination.String(), p.Data)
|
|
}
|