Skip to content

Commit

Permalink
update storage.js
Browse files Browse the repository at this point in the history
  • Loading branch information
54145a committed Oct 30, 2024
1 parent b45dc60 commit ce612be
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions storage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
//54145a.github.io global.js
const UPDATE_MIN_INTERVAL = 1000;

function createDeepProxy(target, handler) {
const deepHandler = Object.assign({}, handler);
deepHandler.get = (target, property) => {
const value = Reflect.get(target, property);
if (typeof value === "object" && value !== null) {
return createDeepProxy(value, handler);
} else {
if (handler.get) {
return handler.get(target, property, void 0);
} else {
return value;
}
}
};
return new Proxy(target, deepHandler);
}
function createStorageObject(defaultValue, updator) {
let scheduledUpdate = false;
let cache = Object.assign({}, defaultValue);
return createDeepProxy(cache, {
set(target, property, value) {
if (!scheduledUpdate) {
scheduledUpdate = true;
setTimeout(async () => {
scheduledUpdate = false;
await updator(cache);
}, UPDATE_MIN_INTERVAL);
}
return Reflect.set(target, property, value);
}
});
}
function getStorage(name) {
const defaultValue = localStorage.getItem(name);
return createStorageObject(
defaultValue ? JSON.parse(defaultValue) : {},
async data => {
localStorage[name] = JSON.stringify(data);
}
);
}
export { getStorage };

0 comments on commit ce612be

Please sign in to comment.