as discussed before, the problem with setDefault() approach you are
suggesting is that the dict(), at least in JS, will be created in any case.

var newDict = a.setDefault(k1, dict());

above operation will invoke dict() regardless k1 was present or less and
this is not good for anyone: RAM, CPU, GC, etc

the initial pattern is and wants to be like that so that not a single
pointless operation is performed when/if the key is already there.

var o = obj.has(key) ? obj.get(key) : obj.set(key, dict()); // <== see
dict, never called if key

quick and dirty

var o = obj.get(key) || obj.set(key, dict());

With current pattern, and my only concern is that after this decision every
other `set()` like pattern will return this even where not optimal, I have
to do

var o = obj.has(key) ? obj.get(key) : obj.set(key, dict()).get(key);

meh ... but I can survive :D











On Tue, Dec 4, 2012 at 4:49 PM, Tab Atkins Jr. <jackalm...@gmail.com> wrote:

> On Mon, Dec 3, 2012 at 2:21 PM, Andrea Giammarchi
> <andrea.giammar...@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
>
_______________________________________________
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss

Reply via email to