All files index.js

100% Statements 32/32
91.67% Branches 11/12
100% Functions 12/12
100% Lines 28/28
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 561x   12x 108x 108x         12x       1x 1x       9x 1x       3x   18x 2x   1x 9x 9x 9x 9x   1x   3x       4x 48x 38x 11x   4x       4x 4x 4x 4x      
module.exports = class Query {
  constructor (data) {
    this.data = data.map(item => {
      item.sortScore = 0
      return item
    })
  }
 
  get results () {
    return this.data
  }
 
  filter (func) {
    this.data = this.data.filter(func)
    return this
  }
 
  filterBy (key, func) {
    this.data = this.data.filter(item => func(item[key]))
    return this
  }
 
  search (key, term, score = 0) {
    switch (typeof term) {
      case 'boolean':
        this.data = this.data.filter(item => item[key] === term)
        break
      case 'string':
        this.data = this.data.filter(item => {
          let regFind = new RegExp(term, 'gi')
          let termMatches = (item[key].match(regFind) || []).length
          item.sortScore += termMatches
          return termMatches
        })
        break
    }
    return this
  }
 
  sort (key = 'sortScore') {
    this.data = this.data.sort((a, b) => {
      if (a[key] < b[key]) return -1
      if (a[key] > b[key]) return 1
      return 0
    })
    return this
  }
 
  paginate (page = 1, perPage = 10) {
    let min = page * perPage - perPage
    let max = min + perPage
    this.data = this.data.slice(min, max)
    return this
  }
}