Created
August 28, 2017 20:27
-
-
Save hex13/d8ec61a4cb001bab4c4b4678b8c784bf to your computer and use it in GitHub Desktop.
how to serialize symbols in JavaScript
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
const reserializer = (mapping) => { | |
const map = new Map(); | |
Object.keys(mapping).forEach(k => map.set(mapping[k], k)); | |
return { | |
serialize: value => map.get(value), | |
deserialize: value => mapping[value], | |
} | |
} | |
// application | |
let savedState; | |
function startApp() { | |
const a = Symbol(); | |
const b = Symbol(); | |
const c = Symbol(); | |
const {serialize, deserialize} = reserializer({a, b, c}); | |
if (savedState) { | |
const state = JSON.parse(savedState).map(deserialize); | |
console.log('restored: ', state); | |
console.log(state[0] === a) | |
console.log(state[1] === b) | |
console.log(state[2] === b) | |
console.log(state[3] === c) | |
} else { | |
savedState = JSON.stringify([a, b, b, c].map(serialize)); | |
} | |
} | |
startApp(); | |
console.log('saved state', savedState) | |
startApp(savedState); | |
// |
For any search engine traveller, keep looking. This ain't it
I doub't you'll find something vastly different. Though improvement over this snippet would be using of some kind of UUID generated for particular symbols (symbol is just unique identifier, so it would be natural to convert it to some kind of UUID and when deserializing - and then recreate Symbol() from string based UUID).
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For any search engine traveller, keep looking. This ain't it