Paginate an In-Memory Array
Slice an array into a page and return metadata such as total pages and whether more results follow, the shape most list endpoints expose.
Code
export function paginate(items, page = 1, limit = 20) {
const safeLimit = Math.min(Math.max(limit, 1), 100);
const totalPages = Math.max(1, Math.ceil(items.length / safeLimit));
const current = Math.min(Math.max(page, 1), totalPages);
const offset = (current - 1) * safeLimit;
return {
data: items.slice(offset, offset + safeLimit),
page: current,
limit: safeLimit,
totalPages,
hasMore: current < totalPages,
};
}Report a problem with this exampleOpens a pre-filled issue on GitHub.