Jason Orendorff wrote:
... In 2000, Guido van Rossum added the dict.setdefault method to
Python in order to address this need.
Six years later, he had come to consider it a failure.
http://mail.python.org/pipermail/python-dev/2006-February/061169.html
I think the setdefault method failed for three reasons:
1. Its second argument was a value, not a factory function.
2. It just wasn't intuitive. Even to the people most familiar with it,
it was always a conscious effort to read or write code using
setdefault.
3. It required programmers to repeat themselves. The default value had
to be specified every place the map was queried rather than just once
at the point where the data structure was created.
...
So, what about ECMAScript? I think problems 2 and 3 apply to the
various getset/getOrSet/getIfAbsentSet ideas proposed in this thread.
Probably not wholly constructive remark, but for the original
#at:ifAbsentPut: from Smalltalk (which I ported as getIfAbsentSet) is
very readable. Maybe not as readable is ES since keyword does not
separate parameters, but I'd say 2 does not suffer as much.
As for 3., it's true. If you can compute the "default" from the key
alone, you proposal below is fine. The question what is the percentage
of cases where the ifAbsentPut: argument value is in fact bound to the
calling context (for which explicit per-call block to compute the value
is better than per-collection[ class]).
Here is my proposal:
WeakMap.prototype.force = function (key) {
if (this.has(key))
return this.get(key);
var v = this.default(key);
this.set(key, v);
return v;
};
If a particular Map or WeakMap is intended to be used with force(),
the program must supply it with a .default() method, which it could do
just by assignment, maps being extensible objects:
var table = new WeakMap;
table.default = function () { return new Array; };
But nice idea, too. If it is fit for 80% of situations, it is probably
better. I still feel a little uneasy about the fact that I must set up
the default for the collection. When to set it? I've got a feeling the
ghost of malloc/free is materializing behind this (that is, problems
with who should set the default method and when). But maybe it is not
the problem; it is used in Python, after all.
Herby
_______________________________________________
es-discuss mailing list
[email protected]
https://mail.mozilla.org/listinfo/es-discuss