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

David Bruant david.bruant at labri.fr
Thu May 12 16:29:05 PDT 2011


Le 13/05/2011 01:19, Mike Samuel a écrit :
> 2011/5/11 David Bruant <david.bruant at labri.fr>:
>> Hi,
>>
>> I've recently been thinking about the case of memoizing. Let's assume that a
>> function f takes an object o as a parameter and that f is a pure function
>> (results only depends on argument).
>> ----
>> function f(o){
>> /* perform a computation, return the result */
>> }
>> ----
>>
>> 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);
>>   };
>> }
> Does this do what you were trying to accomplish with has, but without
> requiring has?
Yes, I'm sorry, I shouldn't have used the word "require".
Your example does work. It is some derivation of what can be found at
http://wiki.ecmascript.org/doku.php?id=harmony:weak_maps&s=weakmap#explicit_soft_own_fields
I get that neither "has" nor "delete" are required, as proves the above
link and your example. Still, I'm confident that the engine would be a
better place to handle it and my point was that there are some use cases
that may do "heavy" usage of a ".has" method on weak maps which in my
opinion is an argument in favor of adding "has" in the WeakMap API.
It turns out, it seems to already be the plan as wrote Mark Miller in a
previous e-mail. The wiki just cannot be updated yet, before consensus
is reached during a TC-39 meeting.

David


More information about the es-discuss mailing list