Skip to content

Instantly share code, notes, and snippets.

@tbranyen
Created December 31, 2021 18:13
Show Gist options
  • Save tbranyen/ffcbcc865b805289d86b5ed684f17938 to your computer and use it in GitHub Desktop.
Save tbranyen/ffcbcc865b805289d86b5ed684f17938 to your computer and use it in GitHub Desktop.
Visible proxy
function makeVisibleProxy() {
const obj = {};
// Own keys must be known ahead of time for this to work
const keys = ['key1', 'key2'];
// Map each known key to the obj, but make the getter "lazy"
keys.forEach(keyName => {
const desc = {
configurable: true,
enumerable: true,
};
Object.defineProperty(desc, 'value', {
get() {
// This could now be lazy if we wanted...
return keyName === 'key1' ? 1 : 2;
},
});
Object.defineProperty(obj, keyName, desc)
});
// Build up a descriptor for the Proxy object
const descriptor = {
get(_, keyName) {
return Reflect.get(obj, keyName);
},
ownKeys() {
return keys;
},
getOwnPropertyDescriptor(target, prop) {
return {
enumerable: true,
configurable: true,
writable: true,
};
},
};
// Create and return the proxy
return new Proxy(obj, descriptor);
}
const p = makeVisibleProxy();
console.log(p); // now shows { key1: 1, key2: 2 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment