-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathPaginate.js
More file actions
95 lines (72 loc) · 1.61 KB
/
Paginate.js
File metadata and controls
95 lines (72 loc) · 1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/**
* Creates a new `Paginate` form a givin `Array`,
* optionally with a specific `Number` of items per page.
*
* @param {Array} data
* @param {Number} [perPage=10]
* @constructor
* @api public
*/
function Paginate (data, perPage) {
if (!data) throw new Error('Required Argument Missing')
if (!(data instanceof Array)) throw new Error('Invalid Argument Type')
this.data = data
this.perPage = perPage || 10
this.currentPage = 0
this.totalPages = Math.ceil(this.data.length / this.perPage)
}
/**
* Calculates the offset.
*
* @return {Number}
* @api private
*/
Paginate.prototype.offset = function () {
return ((this.currentPage - 1) * this.perPage);
}
/**
* Returns the specified `page`.
*
* @param {Number} pageNum
* @return {Array}
* @api public
*/
Paginate.prototype.page = function (pageNum) {
if (pageNum < 1) pageNum = 1
if (pageNum > this.totalPages) pageNum = this.totalPages
this.currentPage = pageNum
var start = this.offset()
, end = start + this.perPage
return this.data.slice(start, end);
}
/**
* Returns the next `page`.
*
* @return {Array}
* @api public
*/
Paginate.prototype.next = function () {
return this.page(this.currentPage + 1);
}
/**
* Returns the previous `page`.
*
* @return {Array}
* @api public
*/
Paginate.prototype.prev = function () {
return this.page(this.currentPage - 1);
}
/**
* Checks if there is a next `page`.
*
* @return {Boolean}
* @api public
*/
Paginate.prototype.hasNext = function () {
return (this.currentPage < this.totalPages)
}
/**
* Expose `Paginate`
*/
if (typeof module !== 'undefined') module.exports = Paginate