A different semantics for WeakMap#get default value
David Bruant
bruant.d at gmail.com
Mon Jan 16 12:09:06 PST 2012
Hi,
I recently wrote some code using WeakMaps and the following pattern
keeps coming over and over:
-----
var v = wm.get(o);
if(v === undefined){
v = someValue;
order.set(o, v);
}
// now, wn has a value for o (either it already did or it's been added)
// v === wm.get(o)
// play with v
-----
The "v === undefined" is fine in my case, because I know I never store
"undefined" as a value.
I thought that maybe the semantics of WeakMap#get could be changed
whenever the key is not used to set the value and return it.
My pattern would be reduced to:
-----
var v = wm.get(o, someValue);
// now, wn has a value for o (either it already did or it's been added)
// v === wm.get(o)
// play with v
-----
Thinking more about the current semantics, I thought that what is
currently done could be achieved a bit differently:
-----
var v = wm.get(o, def);
// almost equivalent to:
var v = wm.get(o) || def;
-----
There is a difference when the vaue stored in the weak map is a falsy value.
My personal experience is to store mostly objects (so truthy) as weak
map values, so I wouldn't be affected. Has anyone else experience in
storing falsy values?
David
More information about the es-discuss
mailing list