Created
February 21, 2019 12:41
-
-
Save msandrini/f418dbd52b3bbc2702982be41549e997 to your computer and use it in GitHub Desktop.
Proxy Object structure
This file contains hidden or 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 handlerMain = { | |
get: function (obj, prop) { | |
return (prop in obj) ? obj[prop] : new Proxy(obj, handlerSub); | |
} | |
}; | |
const handlerSub = { | |
get: function (obj, prop) { | |
return (prop in obj) ? obj[prop] : {}; | |
} | |
}; | |
const proxyStructure = (myObject) => { | |
return new Proxy(myObject, handlerMain); | |
}; | |
const sample = {}; | |
const possiblyUnknownObject = proxyStructure(sample); | |
console.log(possiblyUnknownObject.unknown.unknown); | |
// ABOUT THIS: | |
// This script above is just a small showcase of the Proxy powers | |
// When you verify an object's properties and subproperties | |
// Sometimes you are caught in a web of recursive conditions. Like: | |
// if (obj && obj.sub && obj.sub.subsub && obj.sub.subsub.final) { ... } | |
// With the script above you can just do: | |
// const pObj = proxyStructure(obj); | |
// if (pObj.sub.subsub.final) { ... } | |
// Bear in mind this has a limitation of 3 sublevels, | |
// although it can be easily extended |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment