(Map|Set|WeakMap)#set() returns `this` ?

Tab Atkins Jr. jackalmage at gmail.com
Tue Dec 4 16:49:08 PST 2012


On Mon, Dec 3, 2012 at 2:21 PM, Andrea Giammarchi
<andrea.giammarchi at gmail.com> wrote:
> IMHO, a set(key, value) should return the value as it is when you address a
> value
>
> var o = m.get(k) || m.set(k, v); // o === v
>
> // equivalent of
>
> var o = m[k] || (m[k] = v); // o === v

If this pattern is considered sufficiently useful (I think it is), we
should handle it directly, as Python does.  Python dicts have a
setDefault(key, value) method which implements this pattern exactly -
if the key is in the dict, it returns its associated value (acts like
a plain get()); if it's not, it sets the key to the passed value and
then returns it.  Using this pattern is not only clearer, but avoids
repetition (of "m" and "k" in your example), and actually chains - I
use setDefault all the time when working with nested dicts.

(For example, if I have a sparse 2d structure implemented with nested
dicts, I can safely get/set a terminal value with code like
"a.setDefault(k1, dict()).set(k2, v)".  If that branch hadn't been
touched before, this creates the nested dict for me.  If it has, I
create a throwaway empty dict, which is cheap.  If JS ever grows
macros, you can avoid the junk dict as well.)

I prefer the plain methods to work as they are currently specified,
where they return this.

~TJ


More information about the es-discuss mailing list