Make sure a vertex can't be added twice to a graph

This commit is contained in:
Alex Rock Ancelet 2019-12-18 09:05:58 +01:00
parent 6045f67230
commit 4b0dfd4dcd
No known key found for this signature in database
GPG Key ID: 4A7B1CB0178A73F5
2 changed files with 20 additions and 1 deletions

View File

@ -13,7 +13,13 @@ export default class Graph {
* @returns {Graph} * @returns {Graph}
*/ */
addVertex(newVertex) { 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; return this;
} }

View File

@ -158,6 +158,19 @@ describe('Graph', () => {
expect(addSameEdgeTwice).toThrow(); 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', () => { it('should return the list of all added edges', () => {
const graph = new Graph(true); const graph = new Graph(true);