Rock JS with Defaultdict
Have you ever missed any of Python’s neat packages like defaultdict
when coding in JavaScript? Unfortunately this reflection functionality wasn’t given in JavaScript.
However now thanks to the Proxy API we can intercept property lookups and build a native defaultdict
in JS. Proxies are part of the ECMAScript 6 standard and are already implemented in Edge, Firefox and Chrome (>= 49) (more details).
Starting simple
I have built a pure defaultdict
JS/Node package for which I will show why it’s so pleasant to finally have reflection in JavaScript. In contrast to other implementations, one doesn’t need to use any special getter and it really can be used like it’s Python “brother”. Detailed instructions for its Browsers or Node.Js use are provided on github.
For a start let’s consider this very simply example:
And its similar Python version:
Coding with Defaultdict is fun!
Our first example wasn’t very fascinating as we need for the direct assignment (d.a=1
) the same amount of characters (if whitespaces are removed).
However coding with defaultdict
is a lot of fun! Let’s consider building a 2-kmers counting matrix.
Traditionally we would have written this in JavaScript:
Now let’s have a look at this neat version with defaultdict
. Note that we can save both ifs with which we have to check for the existence and initialization.
Even the Python code is a bit longer!
Where to go
Proxies are already implemented in Edge, Firefox and Chrome (>=49) and for Node.js one can shim them.