Skip to content

Instantly share code, notes, and snippets.

@MikeRalphson
Last active January 25, 2021 09:58
Show Gist options
  • Save MikeRalphson/0e0aa545bbc87ae1388a5b3ee5d0213b to your computer and use it in GitHub Desktop.
Save MikeRalphson/0e0aa545bbc87ae1388a5b3ee5d0213b to your computer and use it in GitHub Desktop.
Automatically extending objects in Javascript
// based on https://hacks.mozilla.org/2015/07/es6-in-depth-proxies-and-reflect/
function Tree(base = {}) {
return new Proxy(base, treeHandler);
}
const treeHandler = {
get: function (target, key, receiver) {
if (!(key in target) && key !== 'toJSON' && key !== Symbol.iterator) {
target[key] = Tree(); // auto-create a sub-Tree
}
return Reflect.get(target, key, receiver);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment