Skip to content

Instantly share code, notes, and snippets.

@atamocius
Last active September 2, 2020 12:34
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/f7299ad7a294719fe3f3e89075a548c9 to your computer and use it in GitHub Desktop.
Save atamocius/f7299ad7a294719fe3f3e89075a548c9 to your computer and use it in GitHub Desktop.
A slightly more practical example of how to use the paging utilities
import {
calcPageNumbers,
calcOffset,
calcPageCount,
getPageItems,
} from './paging-utils';
// We'll use lodash's `clamp` function
import clamp from 'lodash/clamp';
const items = [
'item 0' , 'item 1' , 'item 2' , 'item 3' , 'item 4' ,
'item 5' , 'item 6' , 'item 7' , 'item 8' , 'item 9' ,
'item 10', 'item 11', 'item 12', 'item 13', 'item 14',
'item 15', 'item 16', 'item 17', 'item 18', 'item 19',
'item 20', 'item 21', 'item 22', 'item 23', 'item 24',
'item 25', 'item 26', 'item 27',
]
const itemsPerPage = 5;
const pageCount = calcPageCount(itemsPerPage, items);
const pageNumbers = calcPageNumbers(pageCount);
const result = goToPage(2);
console.log(pageCount); // output: 6
console.log(pageNumbers); // output: [1, 2, 3, 4, 5, 6]
console.log(result); // output: ['item 10', 'item 11', 'item 12', 'item 13', 'item 14']
/**
* @param {number} pageIndex
*/
function goToPage(pageIndex) {
// Ensure that `pageIndex` is within the index range (`0` to `pageCount - 1`)
pageIndex = clamp(pageIndex, 0, pageCount);
const offset = calcOffset(pageIndex, itemsPerPage);
const pageItems = getPageItems(offset, itemsPerPage, items);
return pageItems;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment