Created
December 31, 2021 18:13
-
-
Save tbranyen/ffcbcc865b805289d86b5ed684f17938 to your computer and use it in GitHub Desktop.
Visible proxy
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
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