Skip to content

Commit 80fc69e

Browse files
committed
Added Node Neighbors
1 parent fbd42f7 commit 80fc69e

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

Graphs/NodeNeighbors.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
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+
})()

0 commit comments

Comments
 (0)