Last active
January 25, 2021 09:58
-
-
Save MikeRalphson/0e0aa545bbc87ae1388a5b3ee5d0213b to your computer and use it in GitHub Desktop.
Automatically extending objects in Javascript
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
// 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