Possible Duplicate:
Set undefined javascript property before read
Is there an equivalent of Python's defaultdict in Javascript? This would be a Javascript array where the value returned for a missing key is definable. Something like:
var a = defaultArray("0");
console.log(a['dog']);
// would print 0
If not, how would you implement it?
A defaultdict works exactly like a normal dict, but it is initialized with a function (“default factory”) that takes no arguments and provides the default value for a nonexistent key. A defaultdict will never raise a KeyError. Any key that does not exist gets the value returned by the default factory.
The defaultdict is a subdivision of the dict class. Its importance lies in the fact that it allows each new key to be given a default value based on the type of dictionary being created. A defaultdict can be created by giving its declaration an argument that can have three values; list, set or int.
Defaultdict is a container like dictionaries present in the module collections. Defaultdict is a sub-class of the dictionary class that returns a dictionary-like object. The functionality of both dictionaries and defaultdict are almost same except for the fact that defaultdict never raises a KeyError.
defaultdict means that if a key is not found in the dictionary, then instead of a KeyError being thrown, a new entry is created. The type of this new entry is given by the argument of defaultdict.
No, this is not possible in JavaScript. Btw, you certainly meant Objects (property-value-maps) instead of arrays. Two solutions:
Implement your object as a Proxy
, which is designed to do exactly what you want. Yet, it is only a draft and currently only supported in Firefox' Javascript 1.8.5.
Use a getter function with a string parameter instead of object properties. That function can look up the input key in an internal "dictionary" object, and handle misses programmatically - e.g. creating values dynamically or returning default values.
Of course you could build a factory for such getter functions.
function defaultDict(map, default) {
return function(key) {
if (key in map)
return map[key];
if (typeof default == "function")
return default(key);
return default;
};
}
var a = defaultDict({cat: 1}, 0);
console.log(a('cat')); // 1
console.log(a('dog')); // 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With