Skip to content

Commit 1503325

Browse files
Pierstovaltrekhleb
authored andcommitted
Make sure a vertex can't be added twice to a graph
1 parent e743df6 commit 1503325

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

src/data-structures/graph/Graph.js

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,13 @@ export default class Graph {
1313
* @returns {Graph}
1414
*/
1515
addVertex(newVertex) {
16-
this.vertices[newVertex.getKey()] = newVertex;
16+
const key = newVertex.getKey();
17+
18+
if (this.vertices[key]) {
19+
throw new Error('Vertex has already been added before');
20+
}
21+
22+
this.vertices[key] = newVertex;
1723

1824
return this;
1925
}

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

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,19 @@ describe('Graph', () => {
158158
expect(addSameEdgeTwice).toThrow();
159159
});
160160

161+
it('should throw an error when trying to add vertex twice', () => {
162+
function addSameEdgeTwice() {
163+
const graph = new Graph(true);
164+
const vertexA = new GraphVertex('A');
165+
166+
graph
167+
.addVertex(vertexA)
168+
.addVertex(vertexA);
169+
}
170+
171+
expect(addSameEdgeTwice).toThrow();
172+
});
173+
161174
it('should return the list of all added edges', () => {
162175
const graph = new Graph(true);
163176

0 commit comments

Comments
 (0)