diff --git a/src/data-structures/graph/GraphVertex.js b/src/data-structures/graph/GraphVertex.js index 06c7d67d..34be0fc5 100644 --- a/src/data-structures/graph/GraphVertex.js +++ b/src/data-structures/graph/GraphVertex.js @@ -31,8 +31,9 @@ export default class GraphVertex { getNeighbors() { const edges = this.edges.toArray(); - const neighborsConverter = ({ value }) => { - return value.startVertex === this ? value.endVertex : value.startVertex; + /** @param {LinkedListNode} node */ + const neighborsConverter = (node) => { + return node.value.startVertex === this ? node.value.endVertex : node.value.startVertex; }; // Return either start or end vertex. @@ -47,6 +48,13 @@ export default class GraphVertex { return this.edges.toArray().map(linkedListNode => linkedListNode.value); } + /** + * @return {number} + */ + getDegree() { + return this.edges.toArray().length; + } + /** * @param {GraphEdge} requiredEdge * @returns {boolean} diff --git a/src/data-structures/graph/__test__/GraphVertex.test.js b/src/data-structures/graph/__test__/GraphVertex.test.js index 679f587a..8512c34d 100644 --- a/src/data-structures/graph/__test__/GraphVertex.test.js +++ b/src/data-structures/graph/__test__/GraphVertex.test.js @@ -100,4 +100,26 @@ describe('GraphVertex', () => { expect(vertexA.findEdge(vertexB)).toEqual(edgeAB); expect(vertexA.findEdge(vertexC)).toBeNull(); }); + + it('should calculate vertex degree', () => { + const vertexA = new GraphVertex('A'); + const vertexB = new GraphVertex('B'); + + expect(vertexA.getDegree()).toBe(0); + + const edgeAB = new GraphEdge(vertexA, vertexB); + vertexA.addEdge(edgeAB); + + expect(vertexA.getDegree()).toBe(1); + + const edgeBA = new GraphEdge(vertexB, vertexA); + vertexA.addEdge(edgeBA); + + expect(vertexA.getDegree()).toBe(2); + + vertexA.addEdge(edgeAB); + expect(vertexA.getDegree()).toBe(3); + + expect(vertexA.getEdges().length).toEqual(3); + }); });