@@ -21,13 +21,15 @@ class Graph {
2121 return result
2222 }
2323
24- printGraph ( ) {
24+ printGraph ( output = value => console . log ( value ) ) {
2525 const keys = Object . keys ( this . adjacencyMap )
2626 for ( const i of keys ) {
2727 const values = this . adjacencyMap [ i ]
2828 let vertex = ''
29- for ( const j of values ) { vertex += j + ' ' }
30- console . log ( i + ' -> ' + vertex )
29+ for ( const j of values ) {
30+ vertex += j + ' '
31+ }
32+ output ( i + ' -> ' + vertex )
3133 }
3234 }
3335
@@ -36,7 +38,7 @@ class Graph {
3638 *
3739 * @param {number } source The source vertex to start BFS.
3840 */
39- bfs ( source ) {
41+ bfs ( source , output = value => console . log ( value ) ) {
4042 const queue = [ ]
4143 const visited = new Set ( )
4244 queue . unshift ( [ source , 0 ] ) // level of source is 0
@@ -46,7 +48,7 @@ class Graph {
4648 const node = front [ 0 ]
4749 const level = front [ 1 ]
4850 queue . shift ( ) // remove the front of the queue
49- console . log ( `Visited node ${ node } at level ${ level } .` )
51+ output ( `Visited node ${ node } at level ${ level } .` )
5052 for ( const next of this . adjacencyMap [ node ] ) {
5153 if ( ! visited . has ( next ) ) { // not visited
5254 queue . unshift ( [ next , level + 1 ] ) // level 1 more than current
@@ -68,11 +70,12 @@ const example = () => {
6870 g . addEdge ( 1 , 3 )
6971 g . addEdge ( 2 , 4 )
7072 g . addEdge ( 2 , 5 )
71- console . log ( 'Printing the adjacency list:\n' )
72- g . printGraph ( )
7373
74- // perform a breadth first search
75- console . log ( '\nBreadth first search at node 1:\n' )
74+ // Printing the adjacency list
75+ // g.printGraph()
76+
77+ // Breadth first search at node 1
7678 g . bfs ( 1 )
7779}
78- example ( )
80+
81+ export { Graph , example }
0 commit comments