Skip to content

Instantly share code, notes, and snippets.

@leodutra
Last active October 31, 2019 15:25
Show Gist options
  • Select an option

  • Save leodutra/8ef519dd988654cc0fee1964e9c29f7f to your computer and use it in GitHub Desktop.

Select an option

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()
@leodutra

leodutra commented Aug 22, 2019 via email

Copy link
Copy Markdown
Author

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