File tree Expand file tree Collapse file tree 2 files changed +20
-1
lines changed
src/data-structures/graph Expand file tree Collapse file tree 2 files changed +20
-1
lines changed Original file line number Diff line number Diff 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 }
Original file line number Diff line number Diff 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
You can’t perform that action at this time.
0 commit comments