type CachedItem = string | Promise<string>

/**
 * Provides svg caching functionality to avoid redundant XHR requests.
 * When the retrieved item doesn't exist in cache yet, a request is sent
 * to its 'src' url. The request's promise is cached for that 'src' key
 * and can be used for the whole session without repeating requests.
 */
class Cache {
  cache: Map<string, CachedItem> = new Map()

  add = (src: string, svg: CachedItem) => {
    this.cache.set(src, svg)
  }

  get = (src: string) => {
    const item = this.cache.get(src)

    if (!item) {
      const promise = fetch(src).then(res => res.text())

      this.add(src, promise)

      return promise
    }

    return item
  }

  reset = () => {
    this.cache.clear()
  }
}

const cache = new Cache()

export default cache
