From 808a1e713ffe9c469f3240503ef06f1078bdf609 Mon Sep 17 00:00:00 2001 From: Oleksii Trekhleb Date: Fri, 11 May 2018 16:58:39 +0300 Subject: [PATCH] Make it possible to delete edge from graph. --- src/data-structures/graph/Graph.js | 19 ++++++++ .../graph/__test__/Graph.test.js | 43 +++++++++++++++++++ 2 files changed, 62 insertions(+) diff --git a/src/data-structures/graph/Graph.js b/src/data-structures/graph/Graph.js index 48a1171f..424e6c3c 100644 --- a/src/data-structures/graph/Graph.js +++ b/src/data-structures/graph/Graph.js @@ -88,6 +88,25 @@ export default class Graph { return this; } + /** + * @param {GraphEdge} edge + */ + deleteEdge(edge) { + // Delete edge from the list of edges. + if (this.edges[edge.getKey()]) { + delete this.edges[edge.getKey()]; + } else { + throw new Error('Edge not found in graph'); + } + + // Try to find and end start vertices and delete edge from them. + const startVertex = this.getVertexByKey(edge.startVertex.getKey()); + const endVertex = this.getVertexByKey(edge.endVertex.getKey()); + + startVertex.deleteEdge(edge); + endVertex.deleteEdge(edge); + } + /** * @param {GraphVertex} startVertex * @param {GraphVertex} endVertex diff --git a/src/data-structures/graph/__test__/Graph.test.js b/src/data-structures/graph/__test__/Graph.test.js index c97cc56c..5a544496 100644 --- a/src/data-structures/graph/__test__/Graph.test.js +++ b/src/data-structures/graph/__test__/Graph.test.js @@ -218,4 +218,47 @@ describe('Graph', () => { expect(graph.getWeight()).toBe(10); }); + + it('should be possible to delete edges from graph', () => { + const graph = new Graph(); + + const vertexA = new GraphVertex('A'); + const vertexB = new GraphVertex('B'); + const vertexC = new GraphVertex('C'); + + const edgeAB = new GraphEdge(vertexA, vertexB); + const edgeBC = new GraphEdge(vertexB, vertexC); + const edgeAC = new GraphEdge(vertexA, vertexC); + + graph + .addEdge(edgeAB) + .addEdge(edgeBC) + .addEdge(edgeAC); + + expect(graph.getAllEdges().length).toBe(3); + + graph.deleteEdge(edgeAB); + + expect(graph.getAllEdges().length).toBe(2); + expect(graph.getAllEdges()[0].getKey()).toBe(edgeBC.getKey()); + expect(graph.getAllEdges()[1].getKey()).toBe(edgeAC.getKey()); + }); + + it('should should throw an error when trying to delete not existing edge', () => { + function deleteNotExistingEdge() { + const graph = new Graph(); + + const vertexA = new GraphVertex('A'); + const vertexB = new GraphVertex('B'); + const vertexC = new GraphVertex('C'); + + const edgeAB = new GraphEdge(vertexA, vertexB); + const edgeBC = new GraphEdge(vertexB, vertexC); + + graph.addEdge(edgeAB); + graph.deleteEdge(edgeBC); + } + + expect(deleteNotExistingEdge).toThrowError(); + }); });