SimpleCache

A Map extended as a Cache. Optional KeyExtractor - Function, optional ValueTransformer - Functions, as well as an optional validityPeriod after which an entry is automatically going to be removed.

This script should not be not be installed directly. It is a library for other scripts to include with the meta directive // @require https://update.greatest.deepsurf.us/scripts/405143/815223/SimpleCache.js

  1. // ==UserScript==
  2. // @name SimpleCache
  3. // @namespace hoehleg.userscripts.private
  4. // @version 0.1
  5. // @description A Map extended as a Cache. Optional KeyExtractor - Function, optional ValueTransformer - Functions, as well as an optional validityPeriod after which an entry is automatically going to be removed.
  6. // @author Gerrit Höhle
  7. //
  8. // @grant none
  9. //
  10. // @require https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js
  11. // ==/UserScript==
  12.  
  13. /* jshint esnext: true */
  14. /* globals $, jQuery */
  15. const SimpleCache = (() => {
  16. const cloneObject = (obj) => {
  17. if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) {
  18. return obj;
  19. }
  20. return jQuery.extend(true, {}, obj);
  21. };
  22.  
  23. return class SimpleCache extends Map {
  24. constructor({ keyExtractor = k => k, setValueTransformer = v => cloneObject(v), getValueTransformer = v => cloneObject(v) } = {}) {
  25. super();
  26. Object.assign(this, { keyExtractor, setValueTransformer, getValueTransformer });
  27. }
  28.  
  29. get(key) {
  30. const finalKey = this.keyExtractor(key);
  31. return this.getValueTransformer(super.get(finalKey));
  32. }
  33.  
  34. set(key, value, validityPeriodMs = 0) {
  35. const finalKey = this.keyExtractor(key);
  36. super.set(finalKey, this.setValueTransformer(value));
  37.  
  38. if (validityPeriodMs > 0) {
  39. setTimeout(() => this.delete(finalKey), validityPeriodMs);
  40. }
  41. return this;
  42. }
  43.  
  44. has(key) {
  45. return super.has(this.keyExtractor(key));
  46. }
  47.  
  48. delete(key) {
  49. return super.delete(this.keyExtractor(key));
  50. }
  51. };
  52. })();