Weak maps syntactic sugar

# David Bruant (14 years ago)

harmony:weak_maps defines weak maps as "unordered tables mapping objects to values". It does reminds me objects a lot, but instead of strings, keys are objects. The API (get/set/has/delete) is very close from what is already possible with current objects for which we have syntax constructs for operations basic operations. Could it be considered to use the object syntax constructs? Code could look like the following:

var wm = new WeakMap(); var o = {};

wm[o] = 123; // set console.log(wm[o]); // logs 123 // get if(o in wm){ // has delete wm[o]; // delete }

There is no new syntax. Everything is already here. There would just be a need to slighty change relevant semantics:

  • MemberExpression : MemberExpression [ Expression ] (es5.github.com/#x11.2.1)
  • CallExpression : CallExpression Expression
    • Add branching on baseValue to see if it's an object or weak mapand behave accordingly. (equivalent branching for "delete" and "in" operators)

Of course, other objects constructs (for-in loops...) would be irrelevant in that case.

# Brendan Eich (14 years ago)

We're generally against using the same syntax for notably different semantics. The stringification of the key in obj[key] is fundamental to objects. It does not apply to WeakMaps, so wm[obj] seems like a trap. Sometimes o[x] will convert x to string and index, other times it will use an x object as a weak map key.

# David Bruant (14 years ago)

Le 21/04/2011 02:00, Brendan Eich a écrit :

We're generally against using the same syntax for notably different semantics.

I understand.

The stringification of the key in obj[key] is fundamental to objects. It does not apply to WeakMaps, so wm[obj] seems like a trap. Sometimes o[x] will convert x to string and index, other times it will use an x object as a weak map key.

However, I don't understand this point. If, as I suggested, semantics of "MemberExpression [ Expression ]" was changed to branch depending on "baseValue" (es5.github.com/#x11.2.1) type, then stringification would be performed only when "baseValue" is evaluated as an object and the object would be kept as the key (object reference without stringification) if "baseValue" is evaluated as a weak map.

# Brendan Eich (14 years ago)

On Apr 21, 2011, at 12:57 AM, David Bruant wrote:

The stringification of the key in obj[key] is fundamental to objects. It does not apply to WeakMaps, so wm[obj] seems like a trap. Sometimes o[x] will convert x to string and index, other times it will use an x object as a weak map key. However, I don't understand this point. If, as I suggested, semantics of ...

I know, you are not proposing always to stringify, of course. That was my point: sometimes x is converted to string (depending on base value evaluated from o being an object), other times not (o evaluates to a WeakMap instance).

IOW I was making explicit the "different semantics" you propose "using the same syntax".