using System;
namespace Swan
{
///
/// A utility class to compute paging or batching offsets.
///
public class Paginator
{
///
/// Initializes a new instance of the class.
///
/// The total count of items to page over.
/// The desired size of individual pages.
public Paginator(int totalCount, int pageSize)
{
TotalCount = totalCount;
PageSize = pageSize;
PageCount = ComputePageCount();
}
///
/// Gets the desired number of items per page.
///
public int PageSize { get; }
///
/// Gets the total number of items to page over.
///
public int TotalCount { get; }
///
/// Gets the computed number of pages.
///
public int PageCount { get; }
///
/// Gets the start item index of the given page.
///
/// Zero-based index of the page.
/// The start item index.
public int GetFirstItemIndex(int pageIndex)
{
pageIndex = FixPageIndex(pageIndex);
return pageIndex * PageSize;
}
///
/// Gets the end item index of the given page.
///
/// Zero-based index of the page.
/// The end item index.
public int GetLastItemIndex(int pageIndex)
{
var startIndex = GetFirstItemIndex(pageIndex);
return Math.Min(startIndex + PageSize - 1, TotalCount - 1);
}
///
/// Gets the item count of the given page index.
///
/// Zero-based index of the page.
/// The number of items that the page contains.
public int GetItemCount(int pageIndex)
{
pageIndex = FixPageIndex(pageIndex);
return (pageIndex >= PageCount - 1)
? GetLastItemIndex(pageIndex) - GetFirstItemIndex(pageIndex) + 1
: PageSize;
}
///
/// Fixes the index of the page by applying bound logic.
///
/// Index of the page.
/// A limit-bound index.
private int FixPageIndex(int pageIndex)
{
if (pageIndex < 0) return 0;
return pageIndex >= PageCount ? PageCount - 1 : pageIndex;
}
///
/// Computes the number of pages for the paginator.
///
/// The page count.
private int ComputePageCount()
{
// include this if when you always want at least 1 page
if (TotalCount == 0)
return 0;
return TotalCount % PageSize != 0
? (TotalCount / PageSize) + 1
: TotalCount / PageSize;
}
}
}