Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to "freeze" a Set (or Map)?

while Set is an Object, Object.freeze() works on the object's properties, which evidently Map and Set do not use: eg

let m = new Map();
Object.freeze(m);
m.set( 'key', 55);
m.get( 'key' ) ==> 55

this is the behavior in Chrome, and I expect it's standard.

I understand that one could (sometimes) transform the Set or Map into a normal Object, and then freeze the object. but then key access changes between the unfrozen and frozen version.

like image 669
cc young Avatar asked Jul 20 '15 05:07

cc young


People also ask

Can you freeze an array?

As an object, an array can be frozen; after doing so, its elements cannot be altered and no elements can be added to or removed from the array. freeze() returns the same object that was passed into the function.

How do you freeze objects?

Object.freeze() Method freeze() which is used to freeze an object. Freezing an object does not allow new properties to be added to an object and prevents from removing or altering the existing properties. Object. freeze() preserves the enumerability, configurability, writability and the prototype of the object.

Is object freeze immutable?

Object. freeze() is shallow. It will make the object immutable, but the nested properties and methods inside said object can still be mutated.


1 Answers

Interesting question, but doesn't currently seem like a directly supported feature on a Set or Map object.

Here are some work-arounds I can think of using the Set object as a guide:

  1. You could create a proxy object that removed .add(), .clear() and .delete(), but allowed proxied access to all other methods that just read data. This would hide access to the actual Set object so there would be no way to access it directly and provide proxied access to all other methods.

  2. You could override .add(), .clear() and .delete() on a given Set instance with methods that did nothing or threw an exception which would prevent modification. If you made those override methods non-configurable and then did a .freeze() on the object, those methods couldn't be put back. One could use Set.prototype.add directly on the Set object to still bypass it though.

like image 114
jfriend00 Avatar answered Oct 31 '22 21:10

jfriend00