Last active
June 8, 2018 13:37
-
-
Save Hamzali/83a2b40cc03adc3320d998776c2c30f3 to your computer and use it in GitHub Desktop.
Node - SafeObject
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
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