Skip to content

Instantly share code, notes, and snippets.

@msandrini
Created February 21, 2019 12:41
Show Gist options
  • Save msandrini/f418dbd52b3bbc2702982be41549e997 to your computer and use it in GitHub Desktop.
Save msandrini/f418dbd52b3bbc2702982be41549e997 to your computer and use it in GitHub Desktop.
Proxy Object structure
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