{"size": 1313, "ext": "js", "max_stars_repo_path": "src/cache.js", "max_stars_repo_name": "ggreer/search-index", "max_stars_repo_stars_event_min_datetime": "2015-01-02T00:31:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T13:59:29.000Z", "max_issues_repo_path": "src/cache.js", "max_issues_repo_name": "ggreer/search-index", "max_issues_repo_issues_event_min_datetime": "2015-01-01T21:31:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T11:50:01.000Z", "max_forks_repo_path": "src/cache.js", "max_forks_repo_name": "ggreer/search-index", "max_forks_repo_forks_event_min_datetime": "2015-01-05T13:22:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T09:57:38.000Z"}
{"max_stars_count": 1198, "max_issues_count": 457, "max_forks_count": 165, "avg_line_length": 25.25, "max_line_length": 109, "alphanum_fraction": 0.6230007616}
// A simple LRU cache

module.exports = class Cache {
  constructor (limit = 1000) {
    this.limit = limit // max entries in cache
    this.LRUStore = new Map()
  }

  // check if entry exists for given key
  has (key) {
    return this.LRUStore.has(key)
  }

  // get cached entry, return and promote entry if found
  get (key) {
    const value = this.LRUStore.get(key)
    if (value) {
      // bump value to head of Map as most recently used
      this.set(key, value)
    }
    return value
  }

  // new entry, trim oldest entry if cache length exceeds limit
  set (key, value) {
    // if size limit reached, delete oldest entry
    if (this.LRUStore.size === this.limit) { this.LRUStore.delete(Array.from(this.LRUStore.keys()).shift()) }
    // remove key from current position in cache (if present)
    this.LRUStore.delete(key)
    this.LRUStore.set(key, value)
    return value
  }

  // check if query is cached if it is return/promote, if not then add
  cache (key, q) {
    key = JSON.stringify(key)
    return this.has(key)
      ? new Promise(resolve => resolve(this.get(key)))
      : q.then(
        result => this.set(key, result)
      )
  }

  // clear all entries in cache
  flush () {
    return new Promise(resolve => {
      this.LRUStore = new Map()
      return resolve()
    })
  }
}
