Last active
September 2, 2020 12:09
-
-
Save atamocius/6f5598333bec3aae4258eb4f0c9719b4 to your computer and use it in GitHub Desktop.
A set of JS functions that help in implementing paging.
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 range from 'lodash/range'; | |
/** | |
* Returns the items in a given page. | |
* @template T | |
* @param {number} offset The index offset based on the given `pageIndex` | |
* (precomputed from `calcOffset`). | |
* @param {number} itemsPerPage The number of items per page. | |
* @param {T[]} items The array of items. | |
*/ | |
export function getPageItems(offset, itemsPerPage, items) { | |
return items.slice(offset, offset + itemsPerPage); | |
} | |
/** | |
* Calculates the number of pages. | |
* @template T | |
* @param {number} itemsPerPage The number of items per page. | |
* @param {T[]} items The array of items. | |
*/ | |
export function calcPageCount(itemsPerPage, items) { | |
return Math.ceil(items.length / itemsPerPage); | |
} | |
/** | |
* Calculates the index offset. | |
* @param {number} pageIndex The page number (starting from zero). | |
* @param {number} itemsPerPage The number of items per page. | |
*/ | |
export function calcOffset(pageIndex, itemsPerPage) { | |
return pageIndex * itemsPerPage; | |
} | |
/** | |
* Calculates the page numbers given the page count. | |
* @param {number} pageCount The number of pages available (precomputed from | |
* `calcPageCount`). | |
*/ | |
export function calcPageNumbers(pageCount) { | |
return range(1, pageCount + 1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment