Skip to content Skip to sidebar Skip to footer

Defaultdict Equivalent In Javascript

In python you can have a defaultdict(int) which stores int as values. And if you try to do a 'get' on a key which is not present in the dictionary you get zero as default value. Ca

Solution 1:

You can build one using a JavaScript Proxy

var defaultDict = newProxy({}, {
  get: (target, name) => name in target ? target[name] : 0
})

This lets you use the same syntax as normal objects when accessing properties.

defaultDict.a = 1
console.log(defaultDict.a) // 1
console.log(defaultDict.b) // 0

To clean it up a bit, you can wrap this in a constructor function, or perhaps use the class syntax.

classDefaultDict {
  constructor(defaultVal) {
    returnnewProxy({}, {
      get: (target, name) => name in target ? target[name] : defaultVal
    })
  }
}

const counts = newDefaultDict(0)
console.log(counts.c) // 0

EDIT: The above implementation only works well with primitives. It should handle objects too by taking a constructor function for the default value. Here is an implementation that should work with primitives and constructor functions alike.

classDefaultDict {
  constructor(defaultInit) {
    returnnewProxy({}, {
      get: (target, name) => name in target ?
        target[name] :
        (target[name] = typeof defaultInit === 'function' ?
          newdefaultInit().valueOf() :
          defaultInit)
    })
  }
}


const counts = newDefaultDict(Number)
counts.c++
console.log(counts.c) // 1const lists = newDefaultDict(Array)
lists.men.push('bob')
lists.women.push('alice')
console.log(lists.men) // ['bob']console.log(lists.women) // ['alice']console.log(lists.nonbinary) // []

Solution 2:

Check out pycollections.js:

var collections = require('pycollections');

var dd = new collections.DefaultDict(function(){return0});
console.log(dd.get('missing'));  // 0

dd.setOneNewValue(987, function(currentValue) {
  return currentValue + 1;
});

console.log(dd.items()); // [[987, 1], ['missing', 0]]

Solution 3:

I don't think there is the equivalent but you can always write your own. The equivalent of a dictionary in javascript would be an object so you can write it like so

function defaultDict() {
    this.get = function (key) {
        if (this.hasOwnProperty(key)) {
            return key;
        } else {
            return0;
        }
    }
}

Then call it like so

var myDict = new defaultDict();
myDict[1] = 2;
myDict.get(1);

Solution 4:

A quick dirty hack can be constructed using Proxy

functiondict(factory, origin) {
    returnnewProxy({ ...origin }, {
        get(dict, key) {
            // Ensure that "missed" keys are set into// The dictionary with default valuesif (!dict.hasOwnProperty(key)) {
                dict[key] = factory()
            }

            return dict[key]
        }
    })
}

So the following code:

n = dict(Number, [[0, 1], [1, 2], [2, 4]])

// Zero is the default value mapped into 3assert(n[3] == 0)

// The key must be present after calling factoryassert(Object.keys(n).length == 4)

Solution 5:

Proxies definitely make the syntax most Python-like, and there's a library called defaultdict2 that offers what seems like a pretty crisp and thorough proxy-based implementation that supports nested/recursive defaultdicts, something I really value and am missing in the other answers so far in this thread.

That said, I tend to prefer keeping JS a bit more "vanilla"/"native" using a function-based approach like this proof-of-concept:

classDefaultMap {
  constructor(defaultFn) {
    this.defaultFn = defaultFn;
    this.root = newMap();
  }
  
  put(...keys) {
    let map = this.root;
    
    for (const key of keys.slice(0, -1)) {
      map.has(key) || map.set(key, newMap());
      map = map.get(key);
    }

    const key = keys[keys.length-1];
    map.has(key) || map.set(key, this.defaultFn());
    return {
      set: setterFn => map.set(key, setterFn(map.get(key))),
      mutate: mutationFn =>mutationFn(map.get(key)),
    };
  }
  
  get(...keys) {
    let map = this.root;

    for (const key of keys) {
      map = map?.get(key);
    }

    return map;
  }
}

// Try it:const dm = newDefaultMap(() => []);
dm.put("foo").mutate(v => v.push(1, 2, 3));
dm.put("foo").mutate(v => v.push(4, 5));
console.log(dm.get("foo")); // [1, 2, 3, 4, 5]
dm.put("bar", "baz").mutate(v => v.push("a", "b"));
console.log(dm.get("bar", "baz")); // ["a", "b"]
dm.put("bar", "baz").set(v =>42);
console.log(dm.get("bar", "baz")); // 42
dm.put("bar", "baz").set(v => v + 1);
console.log(dm.get("bar", "baz")); // 43

The constructor of DefaultMap accepts a function that returns a default value for leaf nodes. The basic operations for the structure are put and get, the latter of which is self-explanatory. put generates a chain of nested keys and returns a pair of functions that let you mutate or set the leaf node at the end of these keys. Accessing .root gives you the underlying Map structure.

Feel free to leave a comment if I've overlooked any bugs or miss useful features and I'll toss it in.

Post a Comment for "Defaultdict Equivalent In Javascript"