package utils import ( "math" ) // Default pagination constants const ( DefaultPage = 1 DefaultPageSize = 5 MaxPageSize = 100 ) // PaginationInfo contains all the information needed for pagination type PaginationInfo struct { TotalResults int TotalPages int CurrentPage int Limit int StartIndex int EndIndex int StartPage int EndPage int } // CalculatePagination calculates pagination information based on total results, current page, and limit func CalculatePagination(totalResults, currentPage, limit int) PaginationInfo { if currentPage < 1 { currentPage = 1 } if limit < 1 { limit = DefaultPageSize } totalPages := int(math.Ceil(float64(totalResults) / float64(limit))) if totalPages < 1 { totalPages = 1 } // Ensure current page is within bounds if currentPage > totalPages { currentPage = totalPages } startIndex := (currentPage - 1) * limit endIndex := startIndex + limit if endIndex > totalResults { endIndex = totalResults } // Calculate pagination range for display startPage := 1 endPage := totalPages // Show up to 10 page numbers, centered around current page when possible if totalPages > 10 { if currentPage <= 5 { endPage = 10 } else if currentPage >= totalPages-4 { startPage = totalPages - 9 } else { startPage = currentPage - 4 endPage = currentPage + 5 } } return PaginationInfo{ TotalResults: totalResults, TotalPages: totalPages, CurrentPage: currentPage, Limit: limit, StartIndex: startIndex + 1, // Convert to 1-based for display EndIndex: endIndex, StartPage: startPage, EndPage: endPage, } } // GetPageResults extracts the results for the current page from a slice func GetPageResults[T any](allResults []T, startIndex, endIndex int) []T { if startIndex >= len(allResults) { return []T{} } if endIndex > len(allResults) { endIndex = len(allResults) } return allResults[startIndex:endIndex] }