bucket crud
This commit is contained in:
14
utils/pagination.go
Normal file
14
utils/pagination.go
Normal file
@ -0,0 +1,14 @@
|
||||
package utils
|
||||
|
||||
// Paginate returns a slicle with offset & limit
|
||||
func Paginate[T any](items []T, offset, limit int) []T {
|
||||
if len(items) <= offset {
|
||||
return []T{}
|
||||
}
|
||||
|
||||
if limit > len(items)-offset {
|
||||
limit = len(items) - offset
|
||||
}
|
||||
|
||||
return items[offset : offset+limit]
|
||||
}
|
37
utils/pagination_test.go
Normal file
37
utils/pagination_test.go
Normal file
@ -0,0 +1,37 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPagination(t *testing.T) {
|
||||
|
||||
cases := []struct {
|
||||
Slice []int
|
||||
Offset int
|
||||
Limit int
|
||||
Expected []int
|
||||
}{
|
||||
{
|
||||
Slice: []int{1, 2, 3, 4, 5},
|
||||
Offset: 1,
|
||||
Limit: 4,
|
||||
Expected: []int{2, 3, 4, 5},
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(
|
||||
fmt.Sprintf("%v %d %d %v", tc.Slice, tc.Offset, tc.Limit, tc.Expected),
|
||||
func(t *testing.T) {
|
||||
got := Paginate(tc.Slice, tc.Offset, tc.Limit)
|
||||
|
||||
if !reflect.DeepEqual(got, tc.Expected) {
|
||||
t.Errorf("Expected %v, but got %v", tc.Expected, got)
|
||||
}
|
||||
|
||||
})
|
||||
}
|
||||
|
||||
}
|
Reference in New Issue
Block a user