From 6a86a6aca6215cb4d464b814c34233b001575cd9 Mon Sep 17 00:00:00 2001 From: "(quasar) nebula" Date: Sat, 12 Mar 2022 19:07:22 -0400 Subject: simple data serialization & random pages fixes --- src/data/serialize.js | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 src/data/serialize.js (limited to 'src/data/serialize.js') diff --git a/src/data/serialize.js b/src/data/serialize.js new file mode 100644 index 0000000..9d4e888 --- /dev/null +++ b/src/data/serialize.js @@ -0,0 +1,38 @@ +// serialize-util.js: simple interface and utility functions for converting +// Things into a directly serializeable format + +// Utility functions + +export function id(x) { + return x; +} + +export function toRef(thing) { + return thing?.constructor.getReference(thing); +} + +export function toRefs(things) { + return things?.map(toRef); +} + +export function toContribRefs(contribs) { + return contribs?.map(({ who, what }) => ({who: toRef(who), what})); +} + +// Interface + +export const serializeDescriptors = Symbol(); + +export function serializeThing(thing) { + const descriptors = thing.constructor[serializeDescriptors]; + if (!descriptors) { + throw new Error(`Constructor ${thing.constructor.name} does not provide serialize descriptors`); + } + + return Object.fromEntries(Object.entries(descriptors) + .map(([ property, transform ]) => [property, transform(thing[property])])); +} + +export function serializeThings(things) { + return things.map(serializeThing); +} -- cgit 1.3.0-6-gf8a5