Advertisement
RehabCZ

Preference Storage example

Mar 21st, 2025
486
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
TypeScript 1.75 KB | Source Code | 0 0
  1. /* eslint-disable @typescript-eslint/no-explicit-any */
  2.  
  3. class PreferenceManager {
  4.     private _preferences: Map<string, Preference>;
  5.  
  6.     constructor() {
  7.         this._preferences = new Map();
  8.         for (let i: number = 0; i <= localStorage.length; i++) {
  9.             const key = localStorage.key(i);
  10.             if (key != null && key.startsWith('preference_')) {
  11.                 this._preferences.set(key.replace('preference_', ''), Preference.load(key));
  12.             }
  13.         }
  14.     }
  15.  
  16.     list() {
  17.         const a = [];
  18.         this._preferences.forEach((v, k) => {
  19.             a.push({ name: k, value: v.value });
  20.         });
  21.         return a;
  22.     }
  23.  
  24.     set(key: string, value: any) {
  25.         const name = 'preference_' + key.replace('preference_', '');
  26.         if (this.get(name) == null) {
  27.             this._preferences.set(key, new Preference(name, value));
  28.         }
  29.     }
  30.  
  31.     get(key: string) {
  32.         return this._preferences.get(key);
  33.     }
  34. }
  35.  
  36. class Preference {
  37.     private _name: string;
  38.     private _value: any;
  39.     constructor(name: string, value: any) {
  40.         this._name = 'preference_' + name.replace('preference_', '');
  41.         this._value = value;
  42.         this.save();
  43.     }
  44.  
  45.     public static load(name: string) {
  46.         const val = localStorage.getItem('preference_' + name.replace('preference_', ''));
  47.         if (val != null) return new this(name, JSON.parse(val));
  48.     }
  49.  
  50.     private save() {
  51.         localStorage.removeItem(this._name);
  52.         localStorage.setItem(this._name, JSON.stringify(this._value));
  53.     }
  54.  
  55.     set value(value: any) {
  56.         this._value = value;
  57.         this.save();
  58.     }
  59.  
  60.     get value() {
  61.         return this._value;
  62.     }
  63. }
  64.  
  65. export default PreferenceManager;
  66.  
Tags: html CSS js web ts
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement