Skip to content

Instantly share code, notes, and snippets.

@thomasboyt
Last active February 18, 2016 19:22
Show Gist options
  • Save thomasboyt/5987633 to your computer and use it in GitHub Desktop.
Save thomasboyt/5987633 to your computer and use it in GitHub Desktop.
defaultDict with ES6 proxies. Firefox only!
function defaultDict(default_) {
return new Proxy({}, {
get: function(target, name, receiver) {
// iterator and next are two JS1.7 things Firefox looks for when you
// log an object to the console. pretty sure it's a bug that they trigger
// the get trap.
if (!(name in target) && !(name == '__iterator__'|| name == 'next')) {
target[name] = default_();
}
return target[name];
}
});
}
// Here, the default value of a key is simply an empty object.
var singleDict = defaultDict(Object);
singleDict.foo.bar = "Hello world!";
console.log(singleDict);
// This is a bit cooler: the default value of a key is another defaultDict.
var nestedDict = defaultDict(function() { return defaultDict(Object) });
nestedDict.foo.bar.baz = "Hello ES6!";
console.log(nestedDict);
// adapted from http://docs.python.org/2/library/collections.html#defaultdict-examples
// This example defines the default value of a key to be "zero", so it can be incremented
// without manually writing a conditional to set it if it's undefined.
var s = 'mississippi',
d = defaultDict(function() {return 0});
// bonus thing: "for of" works like "for in" does in literally every other language!
for (k of s) {
d[k] += 1
}
console.log(d);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment