Skip to content

Instantly share code, notes, and snippets.

@diegocasmo
Last active May 11, 2016 14:24
Show Gist options
  • Save diegocasmo/ba6f55521fd9e20e072dbab3f527d642 to your computer and use it in GitHub Desktop.
Save diegocasmo/ba6f55521fd9e20e072dbab3f527d642 to your computer and use it in GitHub Desktop.
This a requireJS module helpful for paginating an array data structure. I have used this module for features like infinite scrolling and others.
// Helper service to paginate an array
// Usage:
// var bigArray = [1, 2, 3, ..., 1000],
// paginatedArray = new ArrayPaginator(bigArray);
// paginatedArray.getFirstPage() <-- will always return the first 10 elements in array
// paginatedArray.getNextPage() <-- will return next 10 elements in array of the next page
/*global define*/
define([], function() {
'use strict';
function ArrayPaginator(array) {
this._setArray(array);
}
ArrayPaginator.prototype._totalPages = 0;
ArrayPaginator.prototype._currentPage = 0;
ArrayPaginator.prototype._perPage = 10;
ArrayPaginator.prototype.getFirstPage = function() {
this._setFirstPage();
return this._getCurrentPage();
};
ArrayPaginator.prototype.getNextPage = function() {
if (this._currentPage <= this._totalPages) {
this._currentPage++;
return this._getCurrentPage();
}
};
ArrayPaginator.prototype._setArray = function(array) {
this._array = array;
this._setFirstPage();
this._setTotalPages();
};
ArrayPaginator.prototype._setFirstPage = function() {
this._currentPage = 0;
};
ArrayPaginator.prototype._setTotalPages = function() {
this._totalPages = Math.ceil(this._array.length / this._perPage);
};
ArrayPaginator.prototype._getCurrentPage = function() {
return this._array.slice(
this._currentPage * this._perPage,
(this._currentPage + 1) * this._perPage
);
};
return ArrayPaginator;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment