Skip to content

Instantly share code, notes, and snippets.

@audinue
Last active October 30, 2020 02:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save audinue/3a3e0709720249bba7415cd2a4c2f571 to your computer and use it in GitHub Desktop.
Save audinue/3a3e0709720249bba7415cd2a4c2f571 to your computer and use it in GitHub Desktop.
Iterable safe plain JavaScript object as map.
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]]
}
}
})
}
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