Skip to content

Commit 5f50bd9

Browse files
committed
Add degree property to GraphVertex.
1 parent e73dc2d commit 5f50bd9

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

src/data-structures/graph/GraphVertex.js

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,9 @@ export default class GraphVertex {
3131
getNeighbors() {
3232
const edges = this.edges.toArray();
3333

34-
const neighborsConverter = ({ value }) => {
35-
return value.startVertex === this ? value.endVertex : value.startVertex;
34+
/** @param {LinkedListNode} node */
35+
const neighborsConverter = (node) => {
36+
return node.value.startVertex === this ? node.value.endVertex : node.value.startVertex;
3637
};
3738

3839
// Return either start or end vertex.
@@ -47,6 +48,13 @@ export default class GraphVertex {
4748
return this.edges.toArray().map(linkedListNode => linkedListNode.value);
4849
}
4950

51+
/**
52+
* @return {number}
53+
*/
54+
getDegree() {
55+
return this.edges.toArray().length;
56+
}
57+
5058
/**
5159
* @param {GraphEdge} requiredEdge
5260
* @returns {boolean}

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

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,4 +100,26 @@ describe('GraphVertex', () => {
100100
expect(vertexA.findEdge(vertexB)).toEqual(edgeAB);
101101
expect(vertexA.findEdge(vertexC)).toBeNull();
102102
});
103+
104+
it('should calculate vertex degree', () => {
105+
const vertexA = new GraphVertex('A');
106+
const vertexB = new GraphVertex('B');
107+
108+
expect(vertexA.getDegree()).toBe(0);
109+
110+
const edgeAB = new GraphEdge(vertexA, vertexB);
111+
vertexA.addEdge(edgeAB);
112+
113+
expect(vertexA.getDegree()).toBe(1);
114+
115+
const edgeBA = new GraphEdge(vertexB, vertexA);
116+
vertexA.addEdge(edgeBA);
117+
118+
expect(vertexA.getDegree()).toBe(2);
119+
120+
vertexA.addEdge(edgeAB);
121+
expect(vertexA.getDegree()).toBe(3);
122+
123+
expect(vertexA.getEdges().length).toEqual(3);
124+
});
103125
});

0 commit comments

Comments
 (0)