Last active
December 16, 2019 09:54
-
-
Save kausters/cab58c1ab71fd6be3cbe4b09d9da59b9 to your computer and use it in GitHub Desktop.
Generate bracketed page list for pagination; no loops or mutation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Calculate start and end page numbers for page list in pagination | |
* | |
* Page list is expanded to the left and right of the current page by the | |
* amount in [bracketing] argument but without exceeding outer bounds. | |
* | |
* For example (7 pages total, bracketing by 2): | |
* [1] 2 3 4 5 | |
* 1 [2] 3 4 5 | |
* 1 2 [3] 4 5 | |
* 2 3 [4] 5 6 | |
* 3 4 [5] 6 7 | |
* 3 4 5 [6] 7 | |
* 3 4 5 6 [7] | |
* | |
* @param {number} page - current page | |
* @param {number} pages - total pages | |
* @param {number} bracketing - number of pages shown before/after current | |
* @returns {number[]} | |
*/ | |
function buildPageList(page, pages, bracketing = 2) { | |
const expansion = bracketing * 2; // Number of extra pages in list | |
const length = expansion + 1; // Total pages in list, incl. current | |
if (pages <= length) { | |
// Not enough pages for the sliding list, simply list them | |
return fillPageList(1, pages); | |
} | |
// Pages must be within low and high boundary (can never be under 1 or over total) | |
const maxBoundary = Math.min(page + bracketing, pages); | |
const minBoundary = Math.max(maxBoundary - expansion, 1); | |
const last = minBoundary + expansion; | |
return fillPageList(minBoundary, last); | |
} | |
/** | |
* Creates an array of dates for display based on a first and last value. | |
* Basically just filling an array with values offset from index. | |
* | |
* @param {number} first | |
* @param {number} last | |
* @returns {number[]} | |
*/ | |
function fillPageList(first, last) { | |
return _.range(first, last + 1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment