Last active
July 26, 2017 08:26
-
-
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.
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 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"); | |
} | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example on how to use the wrapper: