diff --git a/src/core/graph.js b/src/core/graph.js index 474132e..7da26f1 100644 --- a/src/core/graph.js +++ b/src/core/graph.js @@ -904,3 +904,35 @@ export function edgeToParts( const dstParts = NodeAddress.toParts(edge.dst); return {addressParts, srcParts, dstParts}; } + +/* + * When JSON-serialized, the graph has all of the edges in sorted + * order. This makes it possible to compactly represent metadata + * associated with every edge without needing to duplicate the + * (lengthy) edge addresses. + * This method makes it possible for consumers of Graph to package + * metadata in the same way, without needing to manually re-sort the + * edges. + */ +export function sortedEdgeAddressesFromJSON( + json: GraphJSON +): $ReadOnlyArray { + const {edges} = fromCompat(COMPAT_INFO, json); + return edges.map((x) => EdgeAddress.fromParts(x.address)); +} + +/* + * When JSON-serialized, the graph has all of the nodes in sorted + * order. This makes it possible to compactly represent metadata + * associated with every node without needing to duplicate the + * (lengthy) node addresses. + * This method makes it possible for consumers of Graph to package + * metadata in the same way, without needing to manually re-sort the + * nodes. + */ +export function sortedNodeAddressesFromJSON( + json: GraphJSON +): $ReadOnlyArray { + const {nodes} = fromCompat(COMPAT_INFO, json); + return nodes.map((x) => NodeAddress.fromParts(x)); +} diff --git a/src/core/graph.test.js b/src/core/graph.test.js index 82ce949..47dd02c 100644 --- a/src/core/graph.test.js +++ b/src/core/graph.test.js @@ -16,6 +16,8 @@ import { edgeToString, edgeToStrings, edgeToParts, + sortedEdgeAddressesFromJSON, + sortedNodeAddressesFromJSON, } from "./graph"; import {advancedGraph} from "./graphTestUtil"; @@ -1446,4 +1448,21 @@ describe("core/graph", () => { expect(edgeToParts(edge)).toEqual(expected); }); }); + + it("sortedEdgeAddressesFromJSON", () => { + const json = advancedGraph() + .graph1() + .toJSON(); + const sortedEdgeAddresses = sortedEdgeAddressesFromJSON(json); + const expected = sortedEdgeAddresses.slice().sort(); + expect(sortedEdgeAddresses).toEqual(expected); + }); + it("sortedNodeAddressesFromJSON", () => { + const json = advancedGraph() + .graph1() + .toJSON(); + const sortedNodeAddresses = sortedNodeAddressesFromJSON(json); + const expected = sortedNodeAddresses.slice().sort(); + expect(sortedNodeAddresses).toEqual(expected); + }); });