*.empty Idea

C. Scott Ananian ecmascript at cscott.net
Thu Apr 30 22:20:28 UTC 2015


On Thu, Apr 30, 2015 at 5:57 PM, Jordan Harband <ljharb at gmail.com> wrote:

> I don't see how it would be possible in ES6 user code to ever make a
> Map/Set or a Map/Set subclass instance immutable, since
> `Map.prototype.set.call`/`Set.prototype.add.call` will operate on any
> Map/Set-like object's `[[MapData]]`/`[[SetData]]` internal slot. The only
> thing I can think of would be using a Proxy to a collection rather than a
> collection itself.
>

```
var readOnlySet = function(s) {
  s = new Set(s); // if you're paranoid
  var ReadOnlySet = function(){};
  ReadOnlySet.prototype = Object.create(Set.prototype);

['entries','has','keys','values','toString',Symbol.iterator].forEach(function(f){
    ReadOnlySet.prototype[f] = function() { return s[f].apply(s,
arguments); };
  });
  ['add','clear','delete'].forEach(function(f) {
   ReadOnlySet.prototype[f] = function() { throw new TypeError("immutable
set"); };
  });
  ReadOnlySet.prototype.forEach = function(cb, t) {
     return s.forEach(function(v,k,_) { return cb.call(t, v, k, this); },
this);
  };
  Object.defineProperties(ReadOnlySet.prototype, { size: { get: function()
{ return s.size; } } });
  return new ReadOnlySet();
};
```

In English -- hide the real Set object so that nobody can get to it to
mutate it.
  --scott
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20150430/39dd548c/attachment.html>


More information about the es-discuss mailing list