Last active
October 31, 2019 15:25
-
-
Save leodutra/8ef519dd988654cc0fee1964e9c29f7f to your computer and use it in GitHub Desktop.
Immutable JavaScript objects using Proxy and no Object.freeze()
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 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() |
Author
leodutra
commented
Aug 22, 2019
via email
Thanks. Yw!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment