Skip to content

Instantly share code, notes, and snippets.

@bendc
Created December 17, 2015 10:39
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bendc/5223f50c07d576977f70 to your computer and use it in GitHub Desktop.
Save bendc/5223f50c07d576977f70 to your computer and use it in GitHub Desktop.
Object to Map, recursive-style
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);
})();
@bendc
Copy link
Author

bendc commented Dec 17, 2015

Example:

toMap({ foo: 1, bar: 2 }); // => Map { foo: 1, bar: 2 }

@julienw
Copy link

julienw commented Dec 17, 2015

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 :)

@julienw
Copy link

julienw commented Dec 17, 2015

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