Skip to content

Instantly share code, notes, and snippets.

@rwaldron
Created October 5, 2012 00:30
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rwaldron/3837337 to your computer and use it in GitHub Desktop.
Save rwaldron/3837337 to your computer and use it in GitHub Desktop.
How do Map keys get restored after it's been serialized.
Map.prototype.toJSON = function() {
// somehow iterate keys and values into an array pair?
// for now, I'll fake it.
return '[ [ { "foo": "whatever" }, [ 1, 2, 3, 4, 5 ] ], [ {}, "my key is a plain object" ] ]';
};
function Key(foo) {
this.foo = foo;
}
var map = new Map(),
key = new Key("whatever"),
obj = {};
map.set(key, [ 1, 2, 3, 4, 5 ]);
map.set(obj, "my key is a plain object");
console.log( map.get(key) ); // [ 1, 2, 3, 4, 5 ]
console.log( map.get(obj) ); // "my key is a plain object"
console.log( map.toJSON() );
// [ [ { "foo": "whatever" }, [ 1, 2, 3, 4, 5 ] ], [ {}, "my key is a plain object" ] ]
Now imagine this map is stored in some kind of NoSQL
document store and will be later pulled out by some
other functionality in our application.
How are the map keys (references) revived _into_scope_?
console.log( JSON.parse(map.toJSON()) );
Obviously we can revive the Map:
new Map(JSON.parse(map.toJSON()));
But how do "key" and "obj" get restored?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment