mirror of
https://github.com/trekhleb/javascript-algorithms.git
synced 2026-03-13 08:51:02 +08:00
Make sure a vertex can't be added twice to a graph
This commit is contained in:
committed by
Oleksii Trekhleb
parent
e743df6fab
commit
1503325329
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user