Last active
February 18, 2016 19:22
-
-
Save thomasboyt/5987633 to your computer and use it in GitHub Desktop.
defaultDict with ES6 proxies. Firefox only!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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