Skip to content

Commit 808a1e7

Browse files
committed
Make it possible to delete edge from graph.
1 parent cb48efe commit 808a1e7

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

src/data-structures/graph/Graph.js

+19
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,25 @@ export default class Graph {
8888
return this;
8989
}
9090

91+
/**
92+
* @param {GraphEdge} edge
93+
*/
94+
deleteEdge(edge) {
95+
// Delete edge from the list of edges.
96+
if (this.edges[edge.getKey()]) {
97+
delete this.edges[edge.getKey()];
98+
} else {
99+
throw new Error('Edge not found in graph');
100+
}
101+
102+
// Try to find and end start vertices and delete edge from them.
103+
const startVertex = this.getVertexByKey(edge.startVertex.getKey());
104+
const endVertex = this.getVertexByKey(edge.endVertex.getKey());
105+
106+
startVertex.deleteEdge(edge);
107+
endVertex.deleteEdge(edge);
108+
}
109+
91110
/**
92111
* @param {GraphVertex} startVertex
93112
* @param {GraphVertex} endVertex

src/data-structures/graph/__test__/Graph.test.js

+43
Original file line numberDiff line numberDiff line change
@@ -218,4 +218,47 @@ describe('Graph', () => {
218218

219219
expect(graph.getWeight()).toBe(10);
220220
});
221+
222+
it('should be possible to delete edges from graph', () => {
223+
const graph = new Graph();
224+
225+
const vertexA = new GraphVertex('A');
226+
const vertexB = new GraphVertex('B');
227+
const vertexC = new GraphVertex('C');
228+
229+
const edgeAB = new GraphEdge(vertexA, vertexB);
230+
const edgeBC = new GraphEdge(vertexB, vertexC);
231+
const edgeAC = new GraphEdge(vertexA, vertexC);
232+
233+
graph
234+
.addEdge(edgeAB)
235+
.addEdge(edgeBC)
236+
.addEdge(edgeAC);
237+
238+
expect(graph.getAllEdges().length).toBe(3);
239+
240+
graph.deleteEdge(edgeAB);
241+
242+
expect(graph.getAllEdges().length).toBe(2);
243+
expect(graph.getAllEdges()[0].getKey()).toBe(edgeBC.getKey());
244+
expect(graph.getAllEdges()[1].getKey()).toBe(edgeAC.getKey());
245+
});
246+
247+
it('should should throw an error when trying to delete not existing edge', () => {
248+
function deleteNotExistingEdge() {
249+
const graph = new Graph();
250+
251+
const vertexA = new GraphVertex('A');
252+
const vertexB = new GraphVertex('B');
253+
const vertexC = new GraphVertex('C');
254+
255+
const edgeAB = new GraphEdge(vertexA, vertexB);
256+
const edgeBC = new GraphEdge(vertexB, vertexC);
257+
258+
graph.addEdge(edgeAB);
259+
graph.deleteEdge(edgeBC);
260+
}
261+
262+
expect(deleteNotExistingEdge).toThrowError();
263+
});
221264
});

0 commit comments

Comments
 (0)