Skip to content

Instantly share code, notes, and snippets.

@atamocius
Last active September 2, 2020 12:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atamocius/6f5598333bec3aae4258eb4f0c9719b4 to your computer and use it in GitHub Desktop.
Save atamocius/6f5598333bec3aae4258eb4f0c9719b4 to your computer and use it in GitHub Desktop.
A set of JS functions that help in implementing paging.
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