Skip to content

Instantly share code, notes, and snippets.

@panuhorsmalahti
Last active December 4, 2015 15:58
Show Gist options
  • Save panuhorsmalahti/f85beeab58ff13a65268 to your computer and use it in GitHub Desktop.
Save panuhorsmalahti/f85beeab58ff13a65268 to your computer and use it in GitHub Desktop.
Serialize references
function randomID() {
return Math.random();
}
function serialize(obj, store) {
const retVal = {};
store = store || {
root: retVal,
objects: {},
objectIdMap: new Map()
};
const myId = randomID();
store.objects[myId] = retVal;
store.objectIdMap.set(obj, myId);
Object.keys(obj).forEach(key => {
if (typeof obj[key] === "object") {
let id = store.objectIdMap.get(obj[key]);
if (!id) {
id = randomID();
serialize(obj[key], store);
}
retVal[key] = "ref_" + id;
} else if (typeof obj[key] === "string") {
retVal[key] = "string_" + obj[key];
} else {
retVal[key] = obj[key];
}
});
return { object: retVal, store };
}
const myobj = {};
const foo = { key: 5, ref2: myobj };
myobj.circular = foo;
const bar = { ref: foo, num: 3, str: "test" };
const serialized = serialize(bar);
console.log(JSON.stringify({
root: serialized.store.root,
objects: serialized.store.objects })
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment