Created
April 6, 2022 18:31
-
-
Save theraccoonbear/286c7b3242f04deea3b6be310156f6ae to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ 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