lskdb

locale storage key database

  1. // ==UserScript==
  2. // @name lskdb
  3. // @namespace http://tampermonkey.net/
  4. // @version 1.1.3
  5. // @license MIT
  6. // @description locale storage key database
  7. // @author smartacephale
  8. // @match *://*/*
  9. // ==/UserScript==
  10.  
  11. /*
  12. raison d'etre for this insane degenerative garbage:
  13. if you have to store 1000+ unique keys,
  14. you don't have to parse whole json array to check one value
  15. */
  16.  
  17. class LSKDB {
  18. constructor(prefix = 'lsm-', lockKey = 'lsmngr-lock') {
  19. this.prefix = prefix;
  20. this.lockKey = lockKey;
  21. // migration
  22. const old = localStorage.getItem('lsmngr');
  23. if (!old) return;
  24. const list = JSON.parse(old);
  25. localStorage.removeItem('lsmngr');
  26. list.forEach(l => {
  27. const i = localStorage.getItem(l);
  28. if (i) {
  29. const v = JSON.parse(i);
  30. v.forEach(x => this.setKey(x));
  31. }
  32. localStorage.removeItem(l);
  33. });
  34. }
  35.  
  36. getAllKeys() {
  37. const res = [];
  38. for (const key in localStorage) {
  39. if (key.startsWith(this.prefix)) {
  40. res.push(key);
  41. }
  42. }
  43. return res.map(r => r.slice(this.prefix.length));
  44. }
  45.  
  46. getKeys(n = 12) {
  47. const res = [];
  48. for (const key in localStorage) {
  49. if (res.length >= n) break;
  50. if (key.startsWith(this.prefix)) {
  51. res.push(key);
  52. }
  53. }
  54. res.forEach(k => localStorage.removeItem(k));
  55. return res.map(r => r.slice(this.prefix.length));
  56. }
  57.  
  58. hasKey(key) {
  59. return Object.hasOwn(localStorage, `${this.prefix}${key}`);
  60. }
  61.  
  62. removeKey(key) {
  63. localStorage.removeItem(`${this.prefix}${key}`);
  64. }
  65.  
  66. setKey(key) {
  67. localStorage.setItem(`${this.prefix}${key}`, '');
  68. }
  69.  
  70. isLocked() {
  71. const lock = localStorage.getItem(this.lockKey);
  72. const locktime = 5 * 60 * 1000;
  73. return !(!lock || Date.now() - lock > locktime);
  74. }
  75.  
  76. lock(value) {
  77. if (value) {
  78. localStorage.setItem(this.lockKey, Date.now());
  79. } else {
  80. localStorage.removeItem(this.lockKey);
  81. }
  82. }
  83. }