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?

2
  • stackoverflow.com/questions/812961/… Commented Oct 25, 2012 at 0: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. Commented Oct 25, 2012 at 0:42

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Bergi. That's too bad, I was really hoping there was an equivalent.
With some extension in the code to add new values, you will have same functionality that collections.defaultdict py.
I did what @Luchux is talking about in pycollections.js.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.