Skip to content

Instantly share code, notes, and snippets.

@armand1m
Last active March 4, 2018 23:13
Show Gist options
  • Save armand1m/c256872beb8cf0d59050dbbb1272cfef to your computer and use it in GitHub Desktop.
Save armand1m/c256872beb8cf0d59050dbbb1272cfef to your computer and use it in GitHub Desktop.
simple and naive js object pagination implementation
const paginate = (array, pageSize) => {
const numberOfPages = Math.round(array.length / pageSize);
const needsOneMorePage = array.length % pageSize;
const totalNumberOfPages = needsOneMorePage
? numberOfPages + 1
: numberOfPages;
const iterableNumberOfPages = [
...Array(totalNumberOfPages).keys()
];
return iterableNumberOfPages.map((value, index) => {
const startFromIndex = pageSize * index;
const endIndex = startFromIndex + pageSize;
return array.slice(startFromIndex, endIndex);
})
}
module.exports = paginate;
const paginate = require('./paginate');
describe('paginate(arr, pageSize)', () => {
it('should paginate array by 3 items per page', () => {
const firstPage = [
{ id: 1 },
{ id: 2 },
{ id: 3 },
];
const secondPage = [
{ id: 4 },
{ id: 5 },
{ id: 6 },
];
const thirdPage = [
{ id: 7 },
{ id: 8 },
{ id: 9 },
];
const lastPage = [
{ id: 10 },
];
const items = [
...firstPage,
...secondPage,
...thirdPage,
...lastPage
];
const result = helpers.paginate(items, 3);
expect(result.length).toEqual(4);
expect(result[0]).toEqual(firstPage);
expect(result[1]).toEqual(secondPage);
expect(result[2]).toEqual(thirdPage);
expect(result[3]).toEqual(lastPage);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment