Created
October 5, 2012 00:30
-
-
Save rwaldron/3837337 to your computer and use it in GitHub Desktop.
How do Map keys get restored after it's been serialized.
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
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