Add degree property to GraphVertex.

This commit is contained in:
Oleksii Trekhleb 2018-05-09 09:35:34 +03:00
parent e73dc2dfd7
commit 5f50bd9bb2
2 changed files with 32 additions and 2 deletions

View File

@ -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}

View File

@ -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);
});
});