Skip to content

Instantly share code, notes, and snippets.

@theraccoonbear
Created April 6, 2022 18:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theraccoonbear/286c7b3242f04deea3b6be310156f6ae to your computer and use it in GitHub Desktop.
Save theraccoonbear/286c7b3242f04deea3b6be310156f6ae to your computer and use it in GitHub Desktop.
const scalarTypes = ['string', 'number', 'boolean', 'date'];
const isScalar = thing => scalarTypes.indexOf(typeof thing) >= 0;
const detSerConvert = (inp) => {
if (inp instanceof Date) { return inp.toISOString(); }
if (isScalar(inp)) { return inp; }
if (Array.isArray(inp)) { return inp.map(detSerConvert); }
return Object
.keys(inp)
.sort()
.map( k => [ k, isScalar(inp[k]) ? inp[k] : detSerConvert(inp[k]) ] );
};
const detSer = (thing) => JSON.stringify(detSerConvert(thing));
const data = {
quux: "baz",
foo: "bar",
bish: "bash",
when: new Date(),
thing: [1, 2, 3, true, { other: 123, key: "value" }]
};
const ser = detSer(data);
console.log('orig:', data);
console.log('detSer:', ser);
$ node deterministic-serialization.js
orig: {
quux: 'baz',
foo: 'bar',
bish: 'bash',
when: 2022-04-06T18:31:19.568Z,
thing: [ 1, 2, 3, true, { other: 123, key: 'value' } ]
}
detSer: [["bish","bash"],["foo","bar"],["quux","baz"],["thing",[1,2,3,true,[["key","value"],["other",123]]]],["when","2022-04-06T18:31:19.568Z"]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment