A generic way to split an array into pages, with optional callbacks to modify the structure of each page.
var arr = [
{ foo: 'bar' },
{ foo: 'baz' },
{ foo: 'qux' }
];
rampage(arr, 2);
/* [
* [ arr[0], arr[1] ],
* [ arr[2] ]
* ]
*/
Note that a new array is returned; the original arr
is unchanged.
Pass in opts
if you want to create previous/next links or customise the structure of each page:
var opts = {
preProcess: function(pageItems, pageNum, totalPages) {
return {
pageItems: pageItems,
pageNum: pageNum
};
},
postProcess: function(currPage, prevPage, nextPage, pageNum, totalPages) {
currPage.prevPage = prevPage;
currPage.nextPage = nextPage;
return currPage;
}
};
var result = rampage(arr, 2, opts);
/* [
* {
* pageItems: [ arr[0], arr[1] ],
* pageNum: 0,
* prevPage: undefined,
* nextPage: result[1]
* },
* {
* pageItems: [ arr[2] ],
* pageNum: 1,
* prevPage: result[0],
* nextPage: undefined
* }
* ]
*/
-
arr
— An array. -
numPerPage
— A positive integer. -
opts
— Used to define thepreProcess
andpreProcess
callbacks.-
opts.preProcess
maps over each slice ofarr
. It defaults to the identity function, and takes the following arguments:pageItems
— The current slice ofarr
, which would have at mostnumPerPage
number of items.pageNum
— The current page number. Page numbers start from0
.totalPages
— The total number of pages.
-
opts.postProcess
maps over the result ofopts.preProcess
. It takes the following arguments:currPage
— The current page.prevPage
— A reference to the previous page, orundefined
if there is no previous page.nextPage
— A reference to the next page, orundefined
if there is no next page.pageNum
— The current page number. Page numbers start from0
.totalPages
— The total number of pages.
-
Install via npm:
$ npm i --save rampage
- 0.1.0
- Initial release