Paginate a Result Set
An API returns results one page at a time. Given the full items array, a 1-based page number and a pageSize, return:
{ items, page, pageSize, totalItems, totalPages, hasPrev, hasNext }
totalPages is Math.ceil(totalItems / pageSize) (0 for no items). A page number p exists when 1 <= p <= totalPages. items holds the slice for the requested page, or [] when that page does not exist. hasPrev says whether page page - 1 exists and hasNext whether page page + 1 exists. page and pageSize are echoed back unchanged.
Example 1
Input: items = ["a","b","c","d","e"], page = 2, pageSize = 2 Output: {"items":["c","d"],"page":2,"pageSize":2,"totalItems":5,"totalPages":3,"hasPrev":true,"hasNext":true} Explanation: Page 2 of 3 holds the 3rd and 4th items.
Example 2
Input: items = ["a","b","c","d","e"], page = 4, pageSize = 2 Output: {"items":[],"page":4,"pageSize":2,"totalItems":5,"totalPages":3,"hasPrev":true,"hasNext":false} Explanation: Page 4 does not exist, but page 3 does, so hasPrev is true.
Constraints
- 0 <= items.length <= 10^5
- -10 <= page <= 10^5
- 1 <= pageSize <= 1000
Hint 1
Page p covers indexes (p - 1) * pageSize up to but not including p * pageSize.
Hint 2
Write a small exists(p) helper and reuse it for all three checks.
Good practice for: Backend Developer, Full Stack Developer, Frontend Developer, Mobile App Developer, Automation Test Engineer
Run checks your code on 3 sample tests. Submit runs all 8 tests, including hidden ones, and earns points. Use console.log to debug. Python's first run can take a few seconds while it starts.