Created
December 17, 2015 10:39
-
-
Save bendc/5223f50c07d576977f70 to your computer and use it in GitHub Desktop.
Object to Map, recursive-style
This file contains hidden or 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 toMap = (() => { | |
const convert = (obj, map = new Map(), keys = Object.keys(obj).values()) => { | |
const state = keys.next(); | |
if (state.done) return map; | |
const key = state.value; | |
map.set(key, obj[key]); | |
return convert(obj, map, keys); | |
}; | |
return obj => obj instanceof Map ? obj : convert(obj); | |
})(); |
const toMap = (() => {
const convert = (obj, map = new Map(), keys = Object.keys(obj).entries()) => {
const state = keys.next();
if (state.done) return map;
const key = state.value[1];
map.set(key, obj[key]);
return convert(obj, map, keys);
};
return obj => obj instanceof Map ? obj : convert(obj);
})();
works in Firefox :)
Another possibility in Firefox:
const toMap = (() => {
const convert = (obj, map = new Map(), keys = Object.keys(obj)[Symbol.iterator]()) => {
const state = keys.next();
if (state.done) return map;
const key = state.value;
map.set(key, obj[key]);
return convert(obj, map, keys);
};
return obj => obj instanceof Map ? obj : convert(obj);
})();
Symbol.iterator
is the same as values
.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example: