Last active
October 30, 2020 02:35
-
-
Save audinue/3a3e0709720249bba7415cd2a4c2f571 to your computer and use it in GitHub Desktop.
Iterable safe plain JavaScript object as map.
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 objectMap () { | |
return Object.defineProperty(Object.create(null), Symbol.iterator, { | |
configurable: true, // This descriptor is inspired by Map.prototype[Symbol.iterator] | |
writable: true, | |
value: function* () { | |
for (const key in this) { | |
yield [key, this[key]] | |
} | |
} | |
}) | |
} |
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
const map = objectMap() | |
map.foo = 1 | |
map.bar = 2 | |
console.log(map.toString) // undefined | |
console.log({}.toString) // ƒ toString() { [native code] } | |
console.log('foo' in map) // true | |
console.log(map['bar']) // 2 | |
// Akin to PHP's foreach ($map as $k => $v) | |
for (const [k, v] of map) | |
console.log(k, v) // foo 1 | |
// bar 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment