Last active
May 7, 2023 00:12
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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