Created
November 18, 2017 19:54
-
-
Save MorganConrad/6292f0cced9b5327fdebfb2612803a7a to your computer and use it in GitHub Desktop.
Treat ordinary object as Map: `keys(), values(), entries())`
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 mapy(object, andPrototype, andAssign) { | |
const _object = object; | |
let _mapy = { | |
keys() { return Object.keys(_object); }, | |
values() { return _it(true); }, | |
entries() { return _it(false); } | |
} | |
if (andPrototype) | |
Object.setPrototypeOf(_mapy, object); | |
if (andAssign) | |
Object.assign(_mapy, object); | |
return _mapy; | |
function _it(justValues) { | |
let idx = 0; | |
const _keys = Object.keys(_object); | |
return { | |
[Symbol.iterator]() { return this; }, | |
next() { | |
let done = idx >= _keys.length; | |
if (done) | |
return { value: undefined, done: true } | |
else { | |
let k = _keys[idx]; | |
let v = _object[_keys[idx]]; | |
let value = justValues ? v : [k,v]; | |
idx++; | |
return { value, done } | |
} | |
} | |
} | |
} | |
} | |
const o = {a:1, b:2, c:3, foo: function() { console.log("foo"); }}; | |
let m1 = mapy(o); | |
var x = Array.from(m1.keys()); console.dir(x); | |
x = Array.from(m1.values()); console.dir(x); | |
x = Array.from(m1.entries()); console.dir(x); | |
console.log(m1.a); | |
m1 = mapy(o, true, true); | |
console.log(m1.a); | |
m1.foo(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment