mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-09-20 07:43:04 +08:00
Make sure a vertex can't be added twice to a graph
This commit is contained in:
parent
6045f67230
commit
4b0dfd4dcd
@ -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;
|
||||||
}
|
}
|
||||||
|
@ -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);
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user