Skip to content

Commit ddd7f9f

Browse files
committed
Add getNeighbors method to Graph.
1 parent 04a2b08 commit ddd7f9f

2 files changed

Lines changed: 28 additions & 0 deletions

File tree

src/data-structures/graph/Graph.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,13 @@ export default class Graph {
2525
return this.vertices[vertexKey];
2626
}
2727

28+
/**
29+
* @param {GraphVertex} vertex
30+
*/
31+
getNeighbors(vertex) {
32+
return vertex.getNeighbors();
33+
}
34+
2835
/**
2936
* @param {GraphEdge} edge
3037
* @returns {Graph}

src/data-structures/graph/__test__/Graph.test.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,4 +111,25 @@ describe('Graph', () => {
111111
expect(graphEdgeAB).toEqual(edgeAB);
112112
expect(graphEdgeAB.weight).toBe(10);
113113
});
114+
115+
it('should return vertex neighbors', () => {
116+
const graph = new Graph(true);
117+
118+
const vertexA = new GraphVertex('A');
119+
const vertexB = new GraphVertex('B');
120+
const vertexC = new GraphVertex('C');
121+
122+
const edgeAB = new GraphEdge(vertexA, vertexB);
123+
const edgeAC = new GraphEdge(vertexA, vertexC);
124+
125+
graph
126+
.addEdge(edgeAB)
127+
.addEdge(edgeAC);
128+
129+
const neighbors = graph.getNeighbors(vertexA);
130+
131+
expect(neighbors.length).toBe(2);
132+
expect(neighbors[0]).toEqual(vertexB);
133+
expect(neighbors[1]).toEqual(vertexC);
134+
});
114135
});

0 commit comments

Comments
 (0)