Skip to content

Instantly share code, notes, and snippets.

@sjb9774
Last active May 7, 2023 00:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sjb9774/99353681314a946191904f8949c49ff4 to your computer and use it in GitHub Desktop.
Save sjb9774/99353681314a946191904f8949c49ff4 to your computer and use it in GitHub Desktop.
Proxy wrapper for objects that tracks changes in a "draft" object without touching the underlying initial object
const getProxyExample = (initialObject = {}) => {
const buildProxyClosure = () => {
let data = {};
let proxyHandler = {
get(obj, prop) {
return prop in data ? data[prop] : obj[prop];
},
set(obj, prop, value) {
data[prop] = value;
}
};
let getDraftData = () => { return {...data} };
return [getDraftData, proxyHandler];
}
let [getDraftData, proxyHandler] = buildProxyClosure();
let initialObjectCopy = { ...initialObject };
let getInitialData = () => initialObjectCopy;
let getMergedObject = () => {
return { ...getInitialData(), ...getDraftData() };
};
let proxyExample = new Proxy(initialObjectCopy, proxyHandler);
return {proxyExample, getDraftData, getInitialData, getMergedObject}
}
const {proxyExample, getDraftData, getInitialData, getMergedObject} = getProxyExample();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment