Skip to content

Instantly share code, notes, and snippets.

@Hamzali
Last active June 8, 2018 13:37
Show Gist options
  • Save Hamzali/83a2b40cc03adc3320d998776c2c30f3 to your computer and use it in GitHub Desktop.
Save Hamzali/83a2b40cc03adc3320d998776c2c30f3 to your computer and use it in GitHub Desktop.
Node - SafeObject
class SafeObject {
constructor(mainObject) {
this.mainObject = mainObject;
this.configs = {
get: SafeObject.get.bind(this)
}
}
static get (target, prop) {
if (prop in target) {
return target[prop];
}
if (prop in this.mainObject && (this.mainObject[prop].constructor === Array || this.mainObject[prop].constructor === Object)) {
target[prop] = (new SafeObject(this.mainObject[prop])).clone();
}
return target[prop] || this.mainObject[prop];
};
clone() {
return new Proxy({}, this.configs);
};
}
// Example
const a = {c: 1, b: "dkljfsd", d: 13, e: {c: 1, d: {c: 1}}};
const o1 = new SafeObject(a);
const cloneO = o1.clone();
cloneO.c = 2;
cloneO.e.c = 3;
cloneO.e.d.c = 4;
console.log(a);
console.log(cloneO.e.c);
console.log(cloneO.e.d.c);
console.log(cloneO);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment