Created
March 8, 2023 13:55
-
-
Save gordonbrander/1f495be55db2a54554eebd3ab8c7a8a5 to your computer and use it in GitHub Desktop.
Ready-only Proxy - a read-only view over JS objects
This file contains hidden or 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
export const isObject = thing => thing != null && typeof thing === "object" | |
export class ReadOnlyProxyWriteError extends Error {} | |
const ReadOnlyProxyDescriptor = { | |
get: (target, key) => { | |
let value = target[key] | |
if (!isObject(value)) { | |
return value | |
} | |
return readonly(value) | |
}, | |
set: (target, key) => { | |
throw new ReadOnlyProxyWriteError('Cannot write on read-only proxy') | |
}, | |
deleteProperty: (target, key) => { | |
throw new ReadOnlyProxyWriteError('Cannot delete on read-only proxy') | |
} | |
} | |
// Create a read-only proxy over an object. | |
// Sub-properties that are objects also return read-only proxies. | |
export const readonly = obj => new Proxy(obj, ReadOnlyProxyDescriptor) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment