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.
This commit is contained in:
Dandelion Mané 2018-06-08 15:19:13 -07:00 committed by GitHub
parent feef119250
commit d9e2850eb3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 56 additions and 1 deletions

View File

@ -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 {

View File

@ -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 = {