File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Graph {
2
+ // Generic graph: the algorithm works regardless of direction or weight
3
+ constructor ( ) {
4
+ this . edges = [ ]
5
+ }
6
+
7
+ addEdge ( node1 , node2 ) {
8
+ // Adding edges to the graph
9
+ this . edges . push ( {
10
+ node1,
11
+ node2
12
+ } )
13
+ }
14
+
15
+ nodeNeighbors ( node ) {
16
+ // Returns an array with all of the node neighbors
17
+ let neighbors = [ ]
18
+ for ( let i = 0 ; i < this . edges . length ; i ++ ) {
19
+ // Checks if they have an edge between them and if the neighbor is not
20
+ // already in the neighbors array
21
+ if ( this . edges [ i ] . node1 === node && ! ( neighbors . includes ( this . edges [ i ] . node2 ) ) ) {
22
+ neighbors . push ( this . edges [ i ] . node2 )
23
+ }
24
+ else if ( this . edges [ i ] . node2 === node && ! ( neighbors . includes ( this . edges [ i ] . node1 ) ) ) {
25
+ neighbors . push ( this . edges [ i ] . node1 )
26
+ }
27
+ }
28
+ return neighbors
29
+ }
30
+ }
31
+
32
+ ( ( ) => {
33
+ let graph = new Graph ( )
34
+ graph . addEdge ( 1 , 2 )
35
+ graph . addEdge ( 2 , 3 )
36
+ graph . addEdge ( 3 , 5 )
37
+ graph . addEdge ( 1 , 5 )
38
+ console . log ( graph . nodeNeighbors ( 1 ) )
39
+ } ) ( )
You can’t perform that action at this time.
0 commit comments