Advertisement
xDisfigure

Virtual Pagination

Sep 12th, 2019
711
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Pagination
  3.  *
  4.  * Handle page results and meta data from a list of items
  5.  *
  6.  *
  7.  * @use ```
  8.  * pagination = new Pagination()
  9.  * pagination.setLimit(10)
  10.  * pagination.setItems(items)
  11.  * pagination.getResults(1)
  12.  * pagination.getMeta()
  13.  * ```
  14.  */
  15. export class Pagination {
  16.   /**
  17.    * @type {any[]}
  18.    */
  19.   items = []
  20.  
  21.   /**
  22.    * @type {number}
  23.    */
  24.   limit
  25.  
  26.   /**
  27.    * @type {{totalItems: number, totalPage: number, limit: number, page: number}}
  28.    */
  29.   meta
  30.  
  31.   constructor({ limit = 10, items = [] } = {}) {
  32.     this.items = items
  33.     this.limit = limit
  34.     this.meta = {
  35.       totalPage: 1,
  36.       page: 1,
  37.       totalItems: items.length,
  38.       limit,
  39.     }
  40.   }
  41.  
  42.   setItems(value) {
  43.     this.items = value
  44.     const totalItems = this.items.length
  45.     this.setMeta({ totalItems })
  46.   }
  47.  
  48.   getItems() {
  49.     return this.items
  50.   }
  51.  
  52.   setLimit(value) {
  53.     this.limit = value
  54.   }
  55.  
  56.   getLimit() {
  57.     return this.limit
  58.   }
  59.  
  60.   getMeta() {
  61.     return { ...this.meta }
  62.   }
  63.  
  64.   setMeta({ page = 1 }) {
  65.     const totalPage = this.computeMaxPage()
  66.     this.meta = {
  67.       totalPage,
  68.       page,
  69.       totalItems: this.items.length,
  70.       limit: this.limit,
  71.     }
  72.   }
  73.  
  74.   getResults(page) {
  75.     this.setMeta({ page: page > 0 ? page : 1 })
  76.     const index = this.limit * (page - 1)
  77.     return [...this.items].splice(index, this.limit)
  78.   }
  79.  
  80.   computeMaxPage() {
  81.     const divided = this.items.length / this.limit
  82.     const isNaN = divided !== divided
  83.     return isNaN || !divided ? 1 : Math.ceil(divided)
  84.   }
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement