Skip to content

Instantly share code, notes, and snippets.

@PaulMaynard
Created October 18, 2014 16:08
Show Gist options
  • Save PaulMaynard/daa05b5f1f52b9d249e9 to your computer and use it in GitHub Desktop.
Save PaulMaynard/daa05b5f1f52b9d249e9 to your computer and use it in GitHub Desktop.
ES6 Map Accessor Proxy
/**
* Proxy for accessing ES6 Maps like objects.
* Usage example:
*
* var p = new MapProxy();
* p['key'] = 'value';
* if ('key' in p) {
* console.log(p.key);
* }
* delete p.key;
*/
function MapProxy(map = new Map()) {
return new Proxy(map, MapProxy.handlers);
}
MapProxy.handlers = {
get: function get(map, key) {
if (map.has(key)) {
return map.get(key);
} else {
return map[key];
}
},
set: function set(map, key, value) {
map.set(key, value);
},
deleteProperty: function deleteProperty(map, key) {
if (map.has(key)) {
map.delete(key);
return true;
} else {
return false;
}
},
ownKeys: function* ownKeys(map, key) {
yield* map.keys();
},
has: function has(map, key) {
return map.has(key);
},
enumerate: function* enumerate(map) {
yield* map[Symbol.iterator || '@@iterator'];
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment