mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-12-25 22:46:20 +08:00
Add degree property to GraphVertex.
This commit is contained in:
parent
e73dc2dfd7
commit
5f50bd9bb2
@ -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}
|
||||
|
@ -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);
|
||||
});
|
||||
});
|
||||
|
Loading…
Reference in New Issue
Block a user