diff --git a/src/data-structures/graph/Graph.js b/src/data-structures/graph/Graph.js index ba0b6d01..9a9194f2 100644 --- a/src/data-structures/graph/Graph.js +++ b/src/data-structures/graph/Graph.js @@ -13,7 +13,13 @@ export default class Graph { * @returns {Graph} */ addVertex(newVertex) { - this.vertices[newVertex.getKey()] = newVertex; + const key = newVertex.getKey(); + + if (this.vertices[key]) { + throw new Error('Vertex has already been added before'); + } + + this.vertices[key] = newVertex; return this; } diff --git a/src/data-structures/graph/__test__/Graph.test.js b/src/data-structures/graph/__test__/Graph.test.js index 936a69b8..dcae57d8 100644 --- a/src/data-structures/graph/__test__/Graph.test.js +++ b/src/data-structures/graph/__test__/Graph.test.js @@ -158,6 +158,19 @@ describe('Graph', () => { expect(addSameEdgeTwice).toThrow(); }); + it('should throw an error when trying to add vertex twice', () => { + function addSameEdgeTwice() { + const graph = new Graph(true); + const vertexA = new GraphVertex('A'); + + graph + .addVertex(vertexA) + .addVertex(vertexA); + } + + expect(addSameEdgeTwice).toThrow(); + }); + it('should return the list of all added edges', () => { const graph = new Graph(true);