Skip to content

Instantly share code, notes, and snippets.

@hex13
Created August 28, 2017 20:27
Show Gist options
  • Save hex13/d8ec61a4cb001bab4c4b4678b8c784bf to your computer and use it in GitHub Desktop.
Save hex13/d8ec61a4cb001bab4c4b4678b8c784bf to your computer and use it in GitHub Desktop.
how to serialize symbols in JavaScript
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);
//
@hex13
Copy link
Author

hex13 commented Jun 13, 2024

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