From d9e2850eb3c8d90aee6d3a0150b3f1be76f68fd4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dandelion=20Man=C3=A9?= Date: Fri, 8 Jun 2018 15:19:13 -0700 Subject: [PATCH] Implement `Graph.copy` (#370) The implementation is quite simple. The tests are somewhat more comprehensive than in v2 or v1. We now test that copies are equal to the original in a variety of situations. Test plan: Unit tests added. --- src/v3/core/graph.js | 9 +++++++- src/v3/core/graph.test.js | 48 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) diff --git a/src/v3/core/graph.js b/src/v3/core/graph.js index ced3b72..8a74fc3 100644 --- a/src/v3/core/graph.js +++ b/src/v3/core/graph.js @@ -304,7 +304,14 @@ export class Graph { } copy(): Graph { - throw new Error("copy"); + const result = new Graph(); + for (const node of this.nodes()) { + result.addNode(node); + } + for (const edge of this.edges()) { + result.addEdge(edge); + } + return result; } toJSON(): GraphJSON { diff --git a/src/v3/core/graph.test.js b/src/v3/core/graph.test.js index 283f3c4..7214912 100644 --- a/src/v3/core/graph.test.js +++ b/src/v3/core/graph.test.js @@ -799,6 +799,54 @@ describe("core/graph", () => { }); }); + describe("copy", () => { + it("copies can be independently mutated", () => { + const g1 = new Graph(); + const g2 = g1.copy(); + g2.addNode(NodeAddress.fromParts(["foo"])); + expect(g1.equals(g2)).toBe(false); + }); + it("copies are reference-distinct", () => { + const g = new Graph(); + expect(g).not.toBe(g.copy()); + }); + describe("copies are equal to original:", () => { + const src = NodeAddress.fromParts(["src"]); + const dst = NodeAddress.fromParts(["dst"]); + const edge1 = () => ({ + src, + dst, + address: EdgeAddress.fromParts(["edge"]), + }); + function expectCopyEqual(g) { + const copy = g.copy(); + expect(copy.equals(g)).toBe(true); + } + it("empty graph", () => { + expectCopyEqual(new Graph()); + }); + it("graph with node added and removed", () => { + const g = new Graph().addNode(src).removeNode(src); + expectCopyEqual(g); + }); + it("graph with an edge", () => { + const g = new Graph() + .addNode(src) + .addNode(dst) + .addEdge(edge1()); + expectCopyEqual(g); + }); + it("graph with edge added and removed", () => { + const g = new Graph() + .addNode(src) + .addNode(dst) + .addEdge(edge1()) + .removeEdge(edge1().address); + expectCopyEqual(g); + }); + }); + }); + describe("edgeToString", () => { it("works", () => { const edge = {