Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript array with default values (equivalent of Python's defaultdict)? [duplicate]

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?

like image 845
Parand Avatar asked Oct 25 '12 00:10

Parand


People also ask

What is the default value in Defaultdict?

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.

What is Python defaultdict?

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.

What is defaultdict in collections in Python?

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.

What does defaultdict list mean?

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.


1 Answers

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
like image 142
Bergi Avatar answered Sep 18 '22 15:09

Bergi