Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Pagination
- *
- * Handle page results and meta data from a list of items
- *
- *
- * @use ```
- * pagination = new Pagination()
- * pagination.setLimit(10)
- * pagination.setItems(items)
- * pagination.getResults(1)
- * pagination.getMeta()
- * ```
- */
- export class Pagination {
- /**
- * @type {any[]}
- */
- items = []
- /**
- * @type {number}
- */
- limit
- /**
- * @type {{totalItems: number, totalPage: number, limit: number, page: number}}
- */
- meta
- constructor({ limit = 10, items = [] } = {}) {
- this.items = items
- this.limit = limit
- this.meta = {
- totalPage: 1,
- page: 1,
- totalItems: items.length,
- limit,
- }
- }
- setItems(value) {
- this.items = value
- const totalItems = this.items.length
- this.setMeta({ totalItems })
- }
- getItems() {
- return this.items
- }
- setLimit(value) {
- this.limit = value
- }
- getLimit() {
- return this.limit
- }
- getMeta() {
- return { ...this.meta }
- }
- setMeta({ page = 1 }) {
- const totalPage = this.computeMaxPage()
- this.meta = {
- totalPage,
- page,
- totalItems: this.items.length,
- limit: this.limit,
- }
- }
- getResults(page) {
- this.setMeta({ page: page > 0 ? page : 1 })
- const index = this.limit * (page - 1)
- return [...this.items].splice(index, this.limit)
- }
- computeMaxPage() {
- const divided = this.items.length / this.limit
- const isNaN = divided !== divided
- return isNaN || !divided ? 1 : Math.ceil(divided)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement