Argument in favor of adding "has" in the WeakMap API

Oliver Hunt oliver at
Wed May 11 12:44:17 PDT 2011

On May 11, 2011, at 12:38 PM, David Bruant wrote:

> Le 11/05/2011 20:38, felix a écrit :
>> On Wed, May 11, 2011 at 11:16, David Bruant <david.bruant at> wrote:
>>> A memoizer could be written to improve f time performance (by the cost of
>>> memory, of course).
>>> ----
>>> function memoizer(f){
>>>  var cache = WeakMap();
>>>  return function(o){
>>>    var res;
>>>    if(WeakMap.has(o))
>>>      return cache.get(o);
>>>    res = f.apply(this, o);
>>>    cache.set(o, res);
>>>  };
>>> }
>>> ----
>> I'm not sure I understand your code.
>> it's not clear to me why you need .has at all, since you can check the
>> return value of .get instead.  in the case where 'undefined' is a
>> valid value that you would want to memoize, you can store a unique
>> object to represent 'undefined'.
> The ambiguity of "get" returning "undefined" when the key is actually
> undefined or when it is defined but its value is "undefined" already
> happened with objects. The solution to that was the "in" operator (or
> Object.prototype.hasOwnProperty depending on cases). I'm just asking an
> equivalent for weak maps. I agree its not necessary as proved in
> harmony:weak_maps#explicit_soft_own_fields . However, a native
> implementation would be a good addition.

So you want to do
if (map.has(bar))
   wiffle = map.get(bar)

or some such?

The problem here is that you can't guarantee that GC won't happen between those two calls, and therefore you could still end up getting undefined in response to the get.

GC is (from the language's perspective) non-deterministic, so any non-atomic operation with a weak map leads to "non-sensical" behaviour.


More information about the es-discuss mailing list