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