leodutra
1/5/2017 - 7:40 PM

Immutable JavaScript objects using Proxy and no Object.freeze()

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