4 Matching Annotations
  1. Oct 2023
  2. Jun 2023
    1. ```js 'use strict';

      // --------------------------------------------------------------------

      class Cache extends Map { constructor(key) { super() this._key = key this.load() }

      set(k, v) { if (!this.has(k) || v !== this.get(k)) { super.set(k, v) this.save() } }

      delete(k) { if (super.has(k)) { super.delete(k) this.save() } }

      clear() { if (super.size() > 0) { super.clear() this.save() } }

      json() { let obj = Object.create(null)

      for (let k of this.keys()) {
        obj[k] = this.get(k)
      }
      
      return obj
      

      }

      save() { const data = this.json() this._save(this._key, data) this.dump({ data, event: 'SAVE' }) }

      load(s) { const data = this._load(this._key)

      if (typeof data !== 'object') {
        return
      }
      
      super.clear()
      
      for (let k of Object.keys(data)) {
        super.set(k, data[k])
      }
      
      this.dump({ data, event: 'LOAD' })
      

      }

      _save(key, data) {} _load(key) {}

      edit() { let res = window.prompt('Edit cached package URLs', JSON.stringify(this.json(), null, 2))

      if (res !== null) {
        try {
          const data = JSON.parse(res)
      
          super.clear()
      
          for (let k of Object.keys(data)) {
            super.set(k, data[k])
          }
      
          this.save()
        }
        catch (ex) {
          console.warn('Failed to update cache data: %s %o', ex.toString(), ex)
        }
      }
      

      }

      toString() { return ${this.constructor.name}<${this._key}>: keys=[ ${this.keys().sort().join(', ')} ] }

      dump({ data, event }) { console.group(${this.constructor.name}<${this._key}>: ${event || 'STATE'}:) console.info(JSON.stringify(data || this.json(), null, 2)) console.groupEnd() } }

      // --------------------------------------------------------------------

      class GMCache extends Cache { _save(key, data) { GM_setValue(key, JSON.stringify(data || {})) }

      _load(key) { return JSON.parse(GM_getValue(key) || '{}') } }

      // --------------------------------------------------------------------

      class StorageCache extends Cache { constructor(key, session) { super(key)

      this.storage = session ? window.sessionStorage : window.localStorage
      this.load()
      

      }

      _save(key, data) { this.storage.setItem(key, JSON.stringify(data || {})) }

      _load(key) { if (this.storage) { return JSON.parse(this.storage.getItem(key) || '{}') } } }

      // --------------------------------------------------------------------

      let c = new StorageCache('test-data') // c.set('jshint-summary', { name: 'jshint-summary', homepage: 'https://github.com/spiralx/jshint-summary' }) ```

  3. Dec 2022
  4. Jun 2022