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.

JavascriptData Fetching

Code

javascriptsnippet
13 lines
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,
  };
}

How it works

Paginate an In-Memory Array keeps everything in the functions offset and paginate.

The result comes back as an object carrying offset, current, safeLimit, totalPages.

Applying it

The primary signature is export function paginate(items, page = 1, limit = 20)

Import paginate from the file and call it — the rest of the code is implementation detail.

The call returns offset, current, safeLimit, totalPages — destructure what you need at the call site.

Statements that matter

const totalPages = Math.max(1, Math.ceil(items.length / safeLimit));
const current = Math.min(Math.max(page, 1), totalPages);
const safeLimit = Math.min(Math.max(limit, 1), 100);

Interactive Tools for This Topic

FAQ

Does `paginate` modify its input?
It does not. Inputs are only read; the return value is freshly built.
Will the snippet run without installing packages?
Yes, it runs as-is — nothing outside the built-in APIs is referenced. The file defines `offset`, `paginate` at load time.