github.com/gitbundle/modules@v0.0.0-20231025071548-85b91c5c3b01/util/paginate.go (about)

     1  // Copyright 2023 The GitBundle Inc. All rights reserved.
     2  // Copyright 2017 The Gitea Authors. All rights reserved.
     3  // Use of this source code is governed by a MIT-style
     4  // license that can be found in the LICENSE file.
     5  
     6  package util
     7  
     8  import "reflect"
     9  
    10  // PaginateSlice cut a slice as per pagination options
    11  // if page = 0 it do not paginate
    12  func PaginateSlice(list interface{}, page, pageSize int) interface{} {
    13  	if page <= 0 || pageSize <= 0 {
    14  		return list
    15  	}
    16  	if reflect.TypeOf(list).Kind() != reflect.Slice {
    17  		return list
    18  	}
    19  
    20  	listValue := reflect.ValueOf(list)
    21  
    22  	page--
    23  
    24  	if page*pageSize >= listValue.Len() {
    25  		return listValue.Slice(listValue.Len(), listValue.Len()).Interface()
    26  	}
    27  
    28  	listValue = listValue.Slice(page*pageSize, listValue.Len())
    29  
    30  	if listValue.Len() > pageSize {
    31  		return listValue.Slice(0, pageSize).Interface()
    32  	}
    33  
    34  	return listValue.Interface()
    35  }