MCPcopy Create free account
hub / github.com/TheAlgorithms/JavaScript / Graph

Class Graph

Graphs/NodeNeighbors.js:3–31  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1// https://en.wikipedia.org/wiki/Neighbourhood_(graph_theory)
2
3class 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
33export { Graph }
34

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected