Skip to content
Onsite

Implement cursor-based pagination for a list sorted by created_at.

MediumP2Coding

Implement paginate(rows, limit, cursor) for a feed sorted newest first: by created_at descending, and by id descending when two rows have the same created_at.

rows is an array of { id, created_at } (both numbers) in any order. Return { items, nextCursor }:

  • items are the next limit rows after the cursor, in feed order. With no cursor (null or undefined) the page starts at the top.
  • nextCursor is an opaque string that, passed back as cursor, gives the page after the last item of this one. It is null when there are no more rows.
  • The cursor must encode the last item's created_at and id and not a position, so rows inserted or deleted between requests do not cause repeats or gaps.

Example 1

Input
rows with created_at 100, 200, 200 (ids 2, 3), 300, 400; limit = 2
Output
items: created_at 400 and 300; nextCursor: not null
Why
Newest first. A second call with nextCursor returns the two rows at created_at 200, ordered by id 3 then 2.

Constraints

  • 1 <= limit <= 1000
  • created_at values can repeat; (created_at, id) is unique.
  • Treat the cursor as opaque in tests: only use values returned by your own function.

Hints

Run checks the 3 visible tests, Submit all 8.