Here's an example of how to implement pagination in TypeScript:
interface PaginationResult<T> {
data: T[];
total: number;
page: number;
limit: number;
}
function paginate<T>(data: T[], page = 1, limit = 10): PaginationResult<T> {
const startIndex = (page - 1) * limit;
const endIndex = page * limit;
const paginatedData = data.slice(startIndex, endIndex);
const total = data.length;
return {
data: paginatedData,
total,
page,
limit,
};
}
In this example, 'paginate' takes an array of data, a page number, and a limit (number of
items per page) as arguments. It returns an object with the paginated data, the total
number of items, the current page number, and the limit.
To use this function, you can simply call it with your data array, the desired page number,
and the limit:
const data = [];
const page = 2;
const limit = 20;
const result = paginate(data, page, limit);
console.log(result.data);
console.log(result.total);
console.log(result.page);
console.log(result.limit);
This implementation assumes that the data array is already sorted in the desired order. If you
need to sort the data, you can do so before calling the 'paginate' function.