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 }:
itemsare the nextlimitrows after the cursor, in feed order. With no cursor (nullorundefined) the page starts at the top.nextCursoris an opaque string that, passed back ascursor, gives the page after the last item of this one. It isnullwhen there are no more rows.- The cursor must encode the last item's
created_atandidand 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
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 8. ⌘Enter runs, ⌘⇧Enter submits.