Use cases for WeakMap

Allen Wirfs-Brock allen at
Sun May 15 16:27:04 PDT 2011

On May 15, 2011, at 3:41 PM, Sam Tobin-Hochstadt wrote:

> On Sun, May 15, 2011 at 6:31 PM, Allen Wirfs-Brock
> <allen at> wrote:
>> I think I've suggest in the past that what we are currently calling "WeakMap" should just be called "ObjectMap" or something like that.  I can't think of any use case where object identify is used as a map key and you don't want the "WeakMap" semantics.  Essentially "WeakMap" just means "NonLeakyObjectMap".
> It's pretty easy to implement a Set datastructure on top of a Map, and
> if your set's equality is ===, then you'd want a strong
> object-identity-keyed map.  WeakMap semantics would clearly be wrong
> here.

Weakmap are also not enumerable which I believe you need for this sort of set implementation to work (and to be useful). You need to be able to get items that have no exterior references out of the set.  If you can't you might as well collect it.

A possible sloppy Set implementation using WeakMap and an auxiliary Array:

function Set() {
   this.keys = new WeapMap;
   this.entries = [];

Set.prototype.add = function (member) {
   if (!this.keys.get(member))  {

Set.prototype.remove = function (member) {
   let indx = this.keys.get(member);
   if (indx)  {
       delete this.entries[indx];
Set.prototype.add = function (member) {
   return this.keys.has(member);

Set.prototype.forEach= function (f) {

If you are going to have both WeakMap and ObjectMap (ie, NonweakMap) I suspect that you will have more bugs from people using an ObjectMap when they really should be using a WeakMap then visa versa.  The exceptional case is wanting the map to be leaky. Rather than having
Map and WeakMap it would probably be better to have Map and StrongMap.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the es-discuss mailing list