15

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?

Community
  • 1
  • 1
Parand
  • 102,950
  • 48
  • 151
  • 186
  • http://stackoverflow.com/questions/812961/javascript-getters-and-setters-for-dummies – goat Oct 25 '12 at 00:28
  • Bergi and rambo, thanks, but I don't think either of those do what I'm looking for. I'm not looking to implement a.get('dog') - I'm looking for a['dog'] to return some default value. That way the code that uses the array can treat it as a regular array. – Parand Oct 25 '12 at 00:42

1 Answers1

3

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
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375