Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* eslint-disable @typescript-eslint/no-explicit-any */
- class PreferenceManager {
- private _preferences: Map<string, Preference>;
- constructor() {
- this._preferences = new Map();
- for (let i: number = 0; i <= localStorage.length; i++) {
- const key = localStorage.key(i);
- if (key != null && key.startsWith('preference_')) {
- this._preferences.set(key.replace('preference_', ''), Preference.load(key));
- }
- }
- }
- list() {
- const a = [];
- this._preferences.forEach((v, k) => {
- a.push({ name: k, value: v.value });
- });
- return a;
- }
- set(key: string, value: any) {
- const name = 'preference_' + key.replace('preference_', '');
- if (this.get(name) == null) {
- this._preferences.set(key, new Preference(name, value));
- }
- }
- get(key: string) {
- return this._preferences.get(key);
- }
- }
- class Preference {
- private _name: string;
- private _value: any;
- constructor(name: string, value: any) {
- this._name = 'preference_' + name.replace('preference_', '');
- this._value = value;
- this.save();
- }
- public static load(name: string) {
- const val = localStorage.getItem('preference_' + name.replace('preference_', ''));
- if (val != null) return new this(name, JSON.parse(val));
- }
- private save() {
- localStorage.removeItem(this._name);
- localStorage.setItem(this._name, JSON.stringify(this._value));
- }
- set value(value: any) {
- this._value = value;
- this.save();
- }
- get value() {
- return this._value;
- }
- }
- export default PreferenceManager;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement