Page Calculator on Items-Per-Page Change

Difficulty: Easy · Topics: Math, Pagination, UX · Acceptance: 100.0% of 2 submissions

Difficulty: Easy  |  Tags: Math, Pagination, UX

Description

When a user changes the number of items displayed per page, calculate which page they should land on so they continue viewing approximately the same content.

Strategy: Find the middle item of the current page view, then compute which page that item falls on with the new page size.

Implement:

calculateNewPage(currentPage, oldPageSize, newPageSize) → int

Examples

Example 1:

Input:  currentPage = 3, oldPageSize = 10, newPageSize = 25
        (currently viewing items 21-30, middle item ~25)

Output: 1
Explanation: Item 25 is on page 1 with 25 items/page.

Example 2:

Input:  currentPage = 5, oldPageSize = 20, newPageSize = 10
        (currently viewing items 81-100, middle item ~90)

Output: 9
Explanation: Item 90 is on page 9 with 10 items/page.

Example 3:

Input:  currentPage = 1, oldPageSize = 10, newPageSize = 5

Output: 1
Explanation: Middle of page 1 is item 5, which is still on page 1 with size 5.

Constraints

Formula

currentFirstItem  = (currentPage - 1) * oldPageSize + 1
currentMiddleItem = currentFirstItem + floor(oldPageSize / 2)
newPage           = max(1, ceil(currentMiddleItem / newPageSize))

---

## Parsing

Practice this problem

Related problems