From ddd7f9fe0d8f3967b900988894195fc106ea90fb Mon Sep 17 00:00:00 2001 From: Oleksii Trekhleb Date: Wed, 11 Apr 2018 08:42:17 +0300 Subject: [PATCH] Add getNeighbors method to Graph. --- src/data-structures/graph/Graph.js | 7 +++++++ .../graph/__test__/Graph.test.js | 21 +++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/src/data-structures/graph/Graph.js b/src/data-structures/graph/Graph.js index f9e69238..b9699d08 100644 --- a/src/data-structures/graph/Graph.js +++ b/src/data-structures/graph/Graph.js @@ -25,6 +25,13 @@ export default class Graph { return this.vertices[vertexKey]; } + /** + * @param {GraphVertex} vertex + */ + getNeighbors(vertex) { + return vertex.getNeighbors(); + } + /** * @param {GraphEdge} edge * @returns {Graph} diff --git a/src/data-structures/graph/__test__/Graph.test.js b/src/data-structures/graph/__test__/Graph.test.js index 8bc5eead..494fbd14 100644 --- a/src/data-structures/graph/__test__/Graph.test.js +++ b/src/data-structures/graph/__test__/Graph.test.js @@ -111,4 +111,25 @@ describe('Graph', () => { expect(graphEdgeAB).toEqual(edgeAB); expect(graphEdgeAB.weight).toBe(10); }); + + it('should return vertex neighbors', () => { + const graph = new Graph(true); + + const vertexA = new GraphVertex('A'); + const vertexB = new GraphVertex('B'); + const vertexC = new GraphVertex('C'); + + const edgeAB = new GraphEdge(vertexA, vertexB); + const edgeAC = new GraphEdge(vertexA, vertexC); + + graph + .addEdge(edgeAB) + .addEdge(edgeAC); + + const neighbors = graph.getNeighbors(vertexA); + + expect(neighbors.length).toBe(2); + expect(neighbors[0]).toEqual(vertexB); + expect(neighbors[1]).toEqual(vertexC); + }); });