Skip to content

Instantly share code, notes, and snippets.

@leodutra
Last active October 31, 2019 15:25
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leodutra/8ef519dd988654cc0fee1964e9c29f7f to your computer and use it in GitHub Desktop.
Save leodutra/8ef519dd988654cc0fee1964e9c29f7f to your computer and use it in GitHub Desktop.
Immutable JavaScript objects using Proxy and no Object.freeze()
function toImmutableProxy(any) {
switch(typeof any) {
case 'object':
case 'function':
case 'xml':
return new Proxy(any, {
set: function immutableProxySet(target, prop) {
throw new Error('Cannot set property "' +prop +'", this object is immutable.')
},
get: function immutableProxyGet(target, prop) {
return toImmutableProxy(target[prop])
}
})
}
return any
}
function test() {
var source = {b: {c: true}}
console.log('source = {b: {c: true}} -> ', source, JSON.stringify(source))
var proxy = toImmutableProxy(source)
console.log('proxy = toImmutableProxy(source) -> ', proxy)
console.log('proxy.b.c -> ', proxy.b.c)
try {
proxy.b.c = false
}
catch(ex) {
console.log('proxy.b.c = false -> ', ex)
}
try {
proxy.z = true
}
catch(ex) {
console.log('When trying to assign a new property to the proxy\nproxy.z = true -> ', ex)
}
console.log('Then assign a new property to the source\nsource.z = true -> ', (source.z = true))
console.log('Assigned property is accessible\nproxy.z -> ', proxy.z)
}
test()
@red-meadow
Copy link

Very elegant, thanks!

@leodutra
Copy link
Author

leodutra commented Aug 22, 2019 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment