Skip to content

Instantly share code, notes, and snippets.

@aeinbu
Last active July 26, 2017 08:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aeinbu/5cbf5b9bbd154692b21e502991e27567 to your computer and use it in GitHub Desktop.
Save aeinbu/5cbf5b9bbd154692b21e502991e27567 to your computer and use it in GitHub Desktop.
This method creates a read only wrapper around a javascript object, so that you can pass large object without copying them and still avoiding that they are changed.
function wrapInReadOnlyProxy(orig, throwOnSet = false) {
if (typeof orig !== "object") {
return orig;
}
return new Proxy(orig, {
get: function(target, property) {
if (property in target) {
return wrapInReadOnlyProxy(target[property]);
}
return undefined;
},
set: function() {
if (throwOnSet) {
throw new Error("Can't set values on a readonly proxy");
}
}
});
}
@aeinbu
Copy link
Author

aeinbu commented Jul 25, 2017

Example on how to use the wrapper:

let original = {
    a: 42,
    b: "forty-two",
    c: {
        e: 51,
        f: "FIFTY-ONE",
        g: {
            i: 101
        },
        h: ["one", "two", "three"]
    },
    d: [10, 20, 30]
};

let readonly = wrapInReadonlyProxy(original);

readonly.a = 142;
readonly.c.e = 151;
readonly.c.g.i = 1001;
readonly.d[1] = 123;

console.log("After trying to modify 'readonly'");
console.log("original", JSON.stringify(original));
console.log("readonly", JSON.stringify(readonly));

console.log();

original.a = 142;
original.c.e = 151;
original.c.g.i = 1001;
original.d[1] = 123;

console.log("After trying to modify 'original'");
console.log("original", JSON.stringify(original));
console.log("readonly", JSON.stringify(readonly));

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