Created
October 18, 2014 16:08
-
-
Save PaulMaynard/daa05b5f1f52b9d249e9 to your computer and use it in GitHub Desktop.
ES6 Map Accessor Proxy
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
/** | |
* 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