Skip to content

Instantly share code, notes, and snippets.

@codeAdrian
Created May 2, 2023 07:57
Show Gist options
  • Save codeAdrian/53e149fb2b9bdc0cd7ac4d984bdb36bc to your computer and use it in GitHub Desktop.
Save codeAdrian/53e149fb2b9bdc0cd7ac4d984bdb36bc to your computer and use it in GitHub Desktop.
/* PROXY */
const handleGet = (obj, prop) => {
if (prop === "undo") {
const last = obj.history.pop();
if (!last) {
return;
}
const { content, lastUpdated } = last;
Reflect.set(obj, "content", content);
Reflect.set(obj, "lastUpdated", lastUpdated);
return { content, lastUpdated };
}
return Reflect.get(obj, prop);
};
const handleSet = (obj, prop, value) => {
if (prop === "content" && value.length > 0 && value.length < 255) {
const { content, lastUpdated, history = [] } = obj;
const historyUpdated = [...history, { content, lastUpdated }];
if (content && lastUpdated) {
Reflect.set(obj, "history", historyUpdated);
}
Reflect.set(obj, prop, value);
Reflect.set(obj, "lastUpdated", Date.now());
return true;
}
console.error(
"Content length should not be empty and be less than 255 characters"
);
return false;
};
const createDocProxy = (doc) => {
return new Proxy(doc, {
get: handleGet,
set: handleSet
});
};
/* INITIALIZE */
const doc = createDocProxy({
content: "",
lastUpdated: Date.now()
});
/* EVENTS */
const input = document.getElementById("data-input");
function save() {
const value = input.value;
doc.content = value;
}
function undo() {
const previous = doc.undo;
if (!previous) {
return;
}
input.value = doc.content;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment