Last active
March 4, 2018 23:13
-
-
Save armand1m/c256872beb8cf0d59050dbbb1272cfef to your computer and use it in GitHub Desktop.
simple and naive js object pagination implementation
This file contains hidden or 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
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; |
This file contains hidden or 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
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