Skip to content

Instantly share code, notes, and snippets.

@traffisco
Last active August 20, 2021 11:12
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save traffisco/32de8ee2850c437bb367cbc8485fb870 to your computer and use it in GitHub Desktop.
Save traffisco/32de8ee2850c437bb367cbc8485fb870 to your computer and use it in GitHub Desktop.
Make localStorage as simple read/write object
Storage.prototype.proxy = {}
Storage.prototype.getAll = function () {
data = {};
Object.keys(this).forEach(key => {
try {
data[key] = JSON.parse(this[key]);
} catch {
data[key] = this[key];
}
});
this.proxy = data;
return this.proxy;
}
Storage.prototype._setItem = Storage.prototype.setItem;
Storage.prototype.setItem = function(target, prop){
try {
this.proxy[target] = JSON.parse(prop);
} catch {
this.proxy[target] = prop;
}
this._setItem(target,prop);
}
Storage.prototype._removeItem = Storage.prototype.removeItem;
Storage.prototype.removeItem = function(target){
delete this.proxy[target];
this._removeItem(target);
}
Storage.prototype.update = function () {
obj = this.proxy;
Object.keys(obj).forEach(key => {
this._setItem(key, JSON.stringify(obj[key]));
});
Object.keys(this).forEach(key => {
if (!(key in obj)) {
this._removeItem(key);
}
});
}
Storage.prototype.dynamic = new Proxy(localStorage.getAll(), handler = {
get(target, prop) {
if (prop == 'isProxy') return true;
if (typeof target[prop] == 'undefined') return;
if (target[prop] != null && !target[prop].isProxy && typeof target[prop] === 'object') {
target[prop] = new Proxy(target[prop], handler);
}
return Reflect.get(...arguments);
},
set() {
Reflect.set(...arguments);
localStorage.update();
return true;
},
deleteProperty(target, prop) {
if (prop in target) {
if (target instanceof Array) {
target.splice(prop, 1);
} else {
delete target[prop];
}
localStorage.update();
}
return true;
}
});
const storage = localStorage.dynamic;
storage.new = {};
storage.new.one = 1;
storage.new.one; // 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment