-
-
Save rfns/3f3cdda936c94b75b1894c1b7a8d4a5c to your computer and use it in GitHub Desktop.
pagination algorithm
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
import { isNumber } from 'lodash'; | |
/** | |
* Creates an array of page numbers based on the selected page and rangeSize and optionally the last page. | |
* Both parameters are used to define what should be visible in the range. | |
* When lastPage is provided, the resulting range is frozen within lastPage's boundaries. | |
* | |
* @param {Number} page The desired page. | |
* @param {Number} rangeSize The size of the range to be created. | |
* @param {NUmber} lastPage The page used to delimit the max page. | |
* @returns An array with range of the affected pages. | |
*/ | |
export const computeRange = (page = 1, rangeSize = 1, lastPage) => { | |
let computedPage = page; | |
if (page < 0) { | |
return new TypeError('The desired page must be a value bigger than 0.'); | |
} | |
if (rangeSize < 0) { | |
return new RangeError('Cannot build a range with a negative value.'); | |
} | |
let threshould = Math.ceil(rangeSize / 2); | |
if (isNumber(lastPage) && ((page + rangeSize) > lastPage)) { | |
computedPage = (lastPage - threshould) + 1 | |
if (computedPage > page) computedPage = page; | |
} | |
return new Array(rangeSize).fill(1).map((irrelevantValue, index) => { | |
let currentPageIndex = (computedPage + index + threshould) - rangeSize; | |
if (currentPageIndex < index + 1) { | |
currentPageIndex = index + 1; | |
} | |
return currentPageIndex; | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment