Skip to content

Instantly share code, notes, and snippets.

@okikio
Created August 15, 2024 01:43
Show Gist options
  • Save okikio/56885d357b625d7865140bbc367dec6e to your computer and use it in GitHub Desktop.
Save okikio/56885d357b625d7865140bbc367dec6e to your computer and use it in GitHub Desktop.
// Target object
const target = {
foo: 1,
bar: 2,
};
// Fallback object
const fallback = {
bar: 20, // This will be overridden by target's bar
baz: 3,
[Symbol('qux')]: 4,
};
// Apply a proxy
const proxy = new Proxy(target, {
// Intercept property access
get(target, property, receiver) {
if (property in target) {
return Reflect.get(target, property, receiver);
} else if (property in fallback) {
return Reflect.get(fallback, property, receiver);
}
return undefined; // Return undefined if not found
},
// Intercept ownKeys to include keys from both target and fallback
ownKeys(target) {
const targetKeys = Reflect.ownKeys(target);
const fallbackKeys = Reflect.ownKeys(fallback);
return Array.from(new Set([...targetKeys, ...fallbackKeys]));
},
// Intercept getOwnPropertyDescriptor to handle keys from both target and fallback
getOwnPropertyDescriptor(target, property) {
if (Reflect.has(target, property)) {
return Reflect.getOwnPropertyDescriptor(target, property);
} else if (Reflect.has(fallback, property)) {
// Return a property descriptor that makes the property enumerable and configurable
const descriptor = Reflect.getOwnPropertyDescriptor(fallback, property);
return {
...descriptor,
configurable: true, // Ensure the property can be modified or deleted
enumerable: true, // Ensure the property shows up in enumerations
};
}
return undefined;
}
});
// Example usage
console.log({ proxy });
// Deno Prints: { proxy: { foo: 1, bar: 2, baz: 3, [Symbol(qux)]: 4 } }
// Node.js & Bun Prints: { proxy: { foo: 1, bar: 2 } }
// Chrome & Safari Print: { proxy: Proxy {foo: 1, bar: 2} }
// Firefox Prints: Object { proxy: Proxy }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment