Skip to content

Commit

Permalink
Add simple serializer with Set support
Browse files Browse the repository at this point in the history
  • Loading branch information
hubol committed Jan 29, 2024
1 parent b16dd1a commit 02d0cc9
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/lib/object/serializer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
const SetPrefix = '@__Set__@';

function replacer(this: any, key: string, value: any) {
if (value instanceof Set) {
return SetPrefix + JSON.stringify(Array.from(value));
}

return value;
}

function reviver(this: any, key: string, value: any) {
if (typeof value === 'string') {
if (value.startsWith(SetPrefix))
return new Set(JSON.parse(value.substring(SetPrefix.length)));
}

return value;
}

function serialize(value: any) {
return JSON.stringify(value, replacer);
}

function deserialize<T>(text: string): T {
return JSON.parse(text, reviver);
}

export const Serializer = {
serialize,
deserialize,
}
43 changes: 43 additions & 0 deletions test/tests/serializer-sanity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { Serializer } from "../../src/lib/object/serializer";
import { Assert } from "../lib/assert";

export function serializeDeserializeWorks() {
const source = {
set1: new Set([ 'a', 'b', { wtf: 32 } ]),
set2: new Set(),
whatever: {
x: -32,
y: 32,
},
};

const text = Serializer.serialize(source);

Assert(text).toStrictlyBe("{\"set1\":\"@__Set__@[\\\"a\\\",\\\"b\\\",{\\\"wtf\\\":32}]\",\"set2\":\"@__Set__@[]\",\"whatever\":{\"x\":-32,\"y\":32}}");

const sourceClone = Serializer.deserialize<typeof source>(text);

Assert(sourceClone.set1 instanceof Set).toBeTruthy();
Assert(sourceClone.set1.has('a')).toBeTruthy();
Assert(sourceClone.set1.has('b')).toBeTruthy();
Assert(sourceClone.set1.size).toStrictlyBe(3);

Assert(sourceClone.set2 instanceof Set).toBeTruthy();
Assert(sourceClone.set2.size).toStrictlyBe(0);

Assert(sourceClone.whatever.x).toStrictlyBe(-32);
Assert(sourceClone.whatever.y).toStrictlyBe(32);

Assert(Object.keys(sourceClone).length).toStrictlyBe(3);
}

export function canSerializeSetDirectly() {
const source = new Set();

const text = Serializer.serialize(source);

const sourceClone = Serializer.deserialize<typeof source>(text);

Assert(sourceClone instanceof Set).toBeTruthy();
Assert(sourceClone.size).toStrictlyBe(0);
}

0 comments on commit 02d0cc9

Please sign in to comment.